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:

You can go through top 50 core java interview questions for more such questions.

Add Comment