How does try-catch work in Java?
The try-catch block in Java is used to handle exceptions and ensure the program continues running even when an error occurs. Here’s a detailed explanation of how it works:
How try-catch Works
- try Block:
The code that might throw an exception is placed inside the try block.
If an exception occurs in this block, execution is immediately transferred to the corresponding catch block.
- catch Block:
The catch block catches and handles the exception.
You can specify different catch blocks for different exception types.
The first catch block that matches the type of the thrown exception is executed.
- Control Flow:
If no exception occurs in the try block, the catch block is skipped.
After the try (and catch, if applicable) block is executed, the program continues with the next statements.
Syntax
try { // Code that may throw an exception } catch (ExceptionType e) { // Code to handle the exception }
Example
public class TryCatchExample { public static void main(String[] args) { try { int result = 10 / 0; // May throw ArithmeticException System.out.println(“Result: “ + result); } catch (ArithmeticException e) { System.out.println(“Error: Division by zero is not allowed.”); } System.out.println(“Program continues…”); } }
Output:
Error: Division by zero is not allowed. Program continues…
Multiple Catch Blocks
You can use multiple catch blocks to handle different types of exceptions.
The order of catch blocks matters; more specific exceptions should come before general ones.
Example:
public class MultipleCatchExample { public static void main(String[] args) { try { String str = null; System.out.println(str.length()); // Throws NullPointerException } catch (NullPointerException e) { System.out.println(“Null value encountered.”); } catch (Exception e) { System.out.println(“Some other exception occurred.”); } } }
Finally Block
A finally block is optional but used to execute code that must run regardless of whether an exception occurs.
Typically used for resource cleanup (e.g., closing files, releasing database connections).
Example with finally:
import java.io.*;
public class FinallyExample { public static void main(String[] args) { FileReader reader = null; try { reader = new FileReader(“nonexistentfile.txt”); } catch (FileNotFoundException e) { System.out.println(“File not found.”); } finally { System.out.println(“Closing resources…”); } } }
Output:
File not found. Closing resources…
Key Points
-
The try block must be followed by at least one catch or finally block.
-
You can nest try-catch blocks to handle exceptions at different levels.
-
Use specific exceptions in catch blocks to avoid catching unintended exceptions.
-
The finally block runs even if there is a return statement in the try or catch block.
Common Interview Questions
- What happens if an exception occurs in the catch block?
If not handled, it propagates to the next level in the call stack.
- Can you write a try block without a catch block?
Yes, but only if there’s a finally block.
- How is exception propagation managed in nested try-catch blocks?
The inner catch block handles the exception