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
}
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!");
}
}
}
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
}
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");
}
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
Best Practices
- Catch specific exceptions rather than using generic
Exception
- Don't use empty catch blocks (silent exception swallowing)
- Use finally for cleanup operations
- Consider logging exceptions
- 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);
}
}
Top comments (0)