When does finally() block run in the Java?
Consider the following code: What will be the output? (NOTE: The answers are in the color of the background so select the text, so see the answer) public class FinallyTest { public static void main(String[] args) { try { int x = Integer.parseInt(args[0]); return; } catch(Exception e) { System.out.println("There was an exception"); } finally { System.out.println("Ran the finally code"); } } } ******************************* Scenario 1 : No input is given Result: There was an exception Ran the finally code Scenario 2 : Pass '1' as argument on command line Result: Ran the finally code ******************************* Now consider this code: public class FinallyTest 2 { public static void main(String[] args) { try { int x = Integer.parseInt(args[0]); } catch(Exception e) { System.out.println("There was an exception"); return; } finally { System.out.println("Ran the finally code"); } } } ******************************* Scenario 1 : No input is given Result: There was an exception Ran the finally code Scenario 2 : Pass '1' as argument on command line Result: Ran the finally code ******************************* Now consider this code: public class FinallyTest { public static void main(String[] args) { try { int x = Integer.parseInt(args[0]); } catch(Exception e) { System.out.println("There was an exception"); System.exit(0); } finally { System.out.println("Ran the finally code"); } } } ******************************* Scenario 1 : No input is given Result: There was an exception Scenario 2 : Pass '1' as argument on command line Result: Ran the finally code ******************************* Now consider this code: public class FinallyTest { public static void main(String[] args) { try { int x = Integer.parseInt(args[0]); System.exit(0); } catch(Exception e) { System.out.println("There was an exception"); } finally { System.out.println("Ran the finally code"); } } } ******************************* Scenario 1 : No input is given Result: There was an exception Ran the finally code Scenario 2 : Pass '1' as argument on command line Result: No output *******************************
0 Comments:
Post a Comment
<< Home