Sunday, 12 August 2018

TryWithResource java

public class TryWithResource {

        public static void main(String[] args) throws Exception {
            try {
                tryWithResourceException();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            try {
                normalTryException();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        private static void normalTryException() throws Exception {
            MyResource mr = null;
            try {
                mr = new MyResource();
                System.out.println("MyResource created in try block");
                if (true)
                    throw new Exception("Exception in try");
            } finally {
                if (mr != null)
                    mr.close();
               
            }

        }

        private static void tryWithResourceException() throws Exception {
            try (MyResource mr = new MyResource()) {
                System.out.println("MyResource created in try-with-resources");
                if (true)
                    throw new Exception("Exception in try");
            }
        }

        static class MyResource implements AutoCloseable {

            @Override
            public void close() throws Exception {
                System.out.println("Closing MyResource");
                throw new Exception("Exception in Closing");
            }

        }
}
output;


MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in try block
Closing MyResource
Exception in Closing

how its work:
tryWithResourceException called
print: MyResource created in try-with-resources
 before throw exception autoclose will call then print Closing MyResource and throw Exception in closing but its override by Exception in try


normalTryException called
print: MyResource created in try block and throw exception Exception in try but its overrride by finally



No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...