In this post, we will see about can we have try without catch block in java.
Table of Contents
Lets understand with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class TryWithoutCatchMain { public static void main(String args[]) { try { System.out.println("Executing try block"); } finally { System.out.println("Executing finally block"); } } } |
When you execute above program, you will get following output:
1 2 3 4 |
Executing try block Executing finally block |
What happens when you have return statement in try block:
If you have return statement in try block, still finally block executes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.arpit.java2blog; public class TryWithoutCatchMain { public static void main(String args[]) { System.out.println(print()); } public static String print() { try { System.out.println("Executing try block"); return "Return from try block"; } finally { System.out.println("Executing finally block"); } } } |
When you execute above program, you will get following output:
1 2 3 4 5 |
Executing try block Executing finally block Return from try block |
What happens if you have return statement in finally block too
It overrides whatever is returned by try block. Lets understand with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; public class TryWithoutCatchMain { public static void main(String args[]) { System.out.println(print()); } public static String print() { try { System.out.println("Executing try block"); return "Return from try block"; } finally { System.out.println("Executing finally block"); return "Return from finally block"; } } } |
When you execute above program, you will get following output:
1 2 3 4 5 |
Executing try block Executing finally block Return from finally block |
What if exception is thrown in try block
If exception is thrown in try block, still finally block executes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; public class TryWithoutCatchMain { public static void main(String args[]) { System.out.println(print()); } public static int print() { try { throw new NullPointerException(); } finally { System.out.println("Executing finally block"); } } } |
When you execute above program, you will get following output:
1 2 3 4 5 6 |
Executing finally block Exception in thread "main" java.lang.NullPointerException at org.arpit.java2blog.TryWithoutCatchMain.print(TryWithoutCatchMain.java:14) at org.arpit.java2blog.TryWithoutCatchMain.main(TryWithoutCatchMain.java:7) |
As you can see that even if code threw NullPointerException, still finally block got executed.
You can go through top 50 core java interview questions for more such questions.