Can We Have Try without Catch Block in Java

In Java, it’s possible to use a try block without a catch block, but it must be followed either by a finally block or be part of a try-with-resources statement.

Let’s see both cases with the help of examples:

1. try-finally Structure

You can use a try block with a finally block. As you may know, the finally block always executes, even if there is an exception or a return statement in the try block, except in the case of System.exit().

The try-finally structure allows developers to execute clean-up code regardless of whether an exception occurs in the try block. Although no catch block is present to handle exceptions, the finally block ensures that necessary clean-up actions, such as closing file streams or releasing resources, are performed.

Output:

2. try-with-resources Statement

Introduced in Java 7, the try-with-resources statement simplifies resource management by automatically closing resources that implement the AutoCloseable or Closeable interfaces.

Output:

3. FAQs

Now, let’s go through some frequently asked questions related to using a try block without a catch block:

3.1. What Happens When You Have return Statement in try Block?

If you include a return statement within the try block, the finally block will still execute. It’s important to note that the finally block executes before the print() function returns.

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

3.2. What Happens if You Have Return Statement in Finally Block Too?

It overrides whatever the try block returns. Let’s understand this with an example:

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

3.3 What if an Exception Is Thrown in the Try Block?

If an exception is thrown in the try block without catch block, the finally block still executes. The exception is propagated up the call stack until it finds a matching catch block. If no catch block is found, the program may terminate.

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

As you can see, even though the code threw a NullPointerException, the finally block was still executed.

3.4 Why would someone use a try block without a catch block?

A try block might be used without a catch block when the intention is not to handle the exception at that point in the code but to ensure that the finally block executes for cleanup purposes, such as closing resources.

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

Was this post helpful?

Leave a Reply

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