DEV Community

realNameHidden
realNameHidden

Posted on

Can you have a try without a catch in Java?

Yes, in Java, you can have a try block without a catch block as long as it’s paired with a finally block. The finally block runs regardless of whether an exception occurs, typically for cleanup tasks. If an exception is thrown in the try block and there’s no catch block, the exception propagates to the caller or terminates the program if unhandled.

Common Follow-Up Questions

Here are some related questions you might face in an interview, with brief answers:

What’s the purpose of the finally block in Java?

The finally block runs whether an exception is thrown or not. It’s used for cleanup tasks, like closing files or releasing resources.

What happens if an exception is thrown in a try block without a catch?

The exception propagates to the calling method. If no method handles it, the program terminates with a stack trace.

Can you have a standalone try block in Java?

No, a try block must be followed by either a catch block or a finally block (or both). Otherwise, it causes a compilation error.

What’s the difference between try-catch and try-finally?

A try-catch block handles exceptions locally, preventing them from propagating. A try-finally block doesn’t handle exceptions but ensures cleanup code in the finally block runs, and any exception propagates to the caller.

Key Takeaways

In Java, you can have a try block without a catch block if you include a finally block.

The finally block runs regardless of whether an exception occurs, making it ideal for cleanup tasks.

Without a catch block, any exception thrown in the try block propagates to the caller or terminates the program.

A standalone try block is not allowed in Java and will cause a compilation error.

Top comments (0)