DEV Community

Sudhakar V
Sudhakar V

Posted on

Try-Catch in Java

The try-catch block in Java is used for exception handling, allowing you to gracefully handle runtime errors and prevent program crashes.

Basic Syntax

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}
Enter fullscreen mode Exit fullscreen mode

Example

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Multiple Catch Blocks

You can handle different exceptions with multiple catch blocks:

try {
    // Code that might throw different exceptions
} catch (IOException e) {
    // Handle IOException
} catch (SQLException e) {
    // Handle SQLException
} catch (Exception e) {
    // Handle any other exceptions
}
Enter fullscreen mode Exit fullscreen mode

Finally Block

The finally block executes whether an exception occurs or not:

try {
    // Code that might throw an exception
} catch (Exception e) {
    // Handle exception
} finally {
    // Code that always executes (e.g., cleanup code)
    System.out.println("This will always execute");
}
Enter fullscreen mode Exit fullscreen mode

Try-With-Resources

Java 7 introduced try-with-resources for automatic resource management:

try (FileReader fr = new FileReader("file.txt")) {
    // Use the resource
} catch (IOException e) {
    // Handle exception
}
// Resource is automatically closed here
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Catch specific exceptions rather than using generic Exception
  2. Don't use empty catch blocks (silent exception swallowing)
  3. Use finally for cleanup operations
  4. Consider logging exceptions
  5. Throw exceptions early, catch them late

Custom Exceptions

You can also create your own exception classes:

class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)