Can we have try without catch block in java

In this post, we will see about can we have try without catch block in java.

Yes,  we can have try without catch block by using finally block.
You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit().

Lets understand with the help of example.

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

What happens when you 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:

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:

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

What if exception is thrown in try block

If exception is thrown in try block, still finally block executes.

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

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.

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.