Try without Catch in java

One of the most asked Java multi-threading interview questions is if we can have try without catch block in java.

Question

Is it possible to have try without catch block in java

Answer

Yes, it is possible to have try without catch in java by using finally.


You can directly use try with finally block and it will just work fine. You might know that finally block is always executed in case of exception or return statement as well.

Please note that finally won’t get called in case you have used system.exit().
Let’s understand with the help of example.

Output:

In case we throw exception from try block:

Finally block will be executed even if you throw exception from try block.

When you execute above program, you will get following output:

In case if we haveĀ  return statement in try block:

If you have return statement in try block, still finally block executes.

When you execute above program, you will get following output:

In case we have return statement in finally block too:

If you have return statement both in try and finally block, then finally block will override return from try blog.

When you execute above program, you will get following output:

Visit top 50 core java interview questions for more such questions.

Leave a Reply

Your email address will not be published. Required fields are marked *