Exception Handling
Understanding Java Exception Handling
Exception handling is a critical mechanism in Java for managing and responding to unexpected or exceptional events during program execution.
Basic Exception Handling Structure
Try-Catch Block
The fundamental approach to handling exceptions:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Potentially risky code
int result = 10 / 0;
} catch (ArithmeticException e) {
// Handle specific exception
System.out.println("Cannot divide by zero!");
}
}
}
Exception Hierarchy
flowchart TD
A[Throwable] --> B[Error]
A --> C[Exception]
C --> D[RuntimeException]
C --> E[Checked Exceptions]
Types of Exceptions
Exception Type |
Description |
Example |
Checked Exceptions |
Compile-time exceptions |
IOException |
Unchecked Exceptions |
Runtime exceptions |
NullPointerException |
Error |
Serious system-level issues |
OutOfMemoryError |
Advanced Exception Handling Techniques
Multiple Catch Blocks
Handling different exception types:
public class MultiCatchDemo {
public static void main(String[] args) {
try {
// Complex operations
int[] array = new int[5];
array[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error");
} catch (Exception e) {
System.out.println("General exception");
}
}
}
Finally Block
Ensuring code execution regardless of exceptions:
public class FinallyDemo {
public static void main(String[] args) {
try {
// Resource-intensive operation
System.out.println("Try block");
} catch (Exception e) {
System.out.println("Catch block");
} finally {
// Always executed
System.out.println("Finally block");
}
}
}
Custom Exception Handling
Creating Custom Exceptions
public class CustomExceptionDemo {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("Invalid age: " + age);
}
}
static class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
}
Best Practices with LabEx
At LabEx, we emphasize:
- Specific exception handling
- Avoiding broad exception catching
- Logging exceptions
- Providing meaningful error messages
Key Principles
- Handle exceptions at the appropriate level
- Use specific exception types
- Never suppress exceptions without proper handling
- Close resources in finally blocks
- Log exceptions for debugging
Common Pitfalls to Avoid
- Catching
Throwable
- Empty catch blocks
- Throwing generic exceptions
- Overlooking resource management
Effective exception handling is crucial for creating robust and reliable Java applications.