In Java, exceptions represent abnormal program states. Understanding and handling exceptions effectively is crucial for robust application development.
Exception Hierarchy
All exception classes inherit from Throwable, which has two main subclasses:
Error: Represents severe issues that typically cannot be handled programmatically (e.g., hardware failures)Exception: Represents general error conditions encountered during program execution
Exceptions are further categorized into checked exceptions (detected at compile time) and unchecked exceptions (detected at runtime, e.g., NullPointerException).
Common Exception Types
| Exception Type | Description |
|---|---|
ArrayIndexOutOfBoundsException |
Thrown when an array is accessed with an invalid index |
NullPointerException |
Thrown when attempting to access a null object reference |
ArithmeticException |
Thrown during arithmetic operations (e.g., division by zero) |
Throwable Methods
Key methods for exception handling:
getMessage(): Retrieves the exception messageprintStackTrace(): Prints the stack trace (default to standard error)printStackTrace(PrintStream): Prints stack trace to a specified stream
Exception Handling Techniques
1. Handling Exceptionns
Use a try-catch block to manage potential exceptions:
try {
// Code that may throw exceptions
} catch (ExceptionType1 exception) {
// Handle ExceptionType1
} catch (ExceptionType2 exception) {
// Handle ExceptionType2
} finally {
// Cleanup code that always executes
}
When catching multiple exceptions, arrange them from most specific to most general to avoid masking specific exceptions.
2. Declaring Exceptions
Use the throws keyword in method signatures to declare potential exceptions:
public void exampleMethod() throws IOException, SQLException {
// Method implementation
}
This informs callers that they must handle the declared exceptions either through a try-catch block or by declaring them in their own method signatures.
3. Throwing Exceptions
Use the throw keyword to manually throw exceptions:
throw new ExceptionType("Exception message");
For example, to throw a custom exception:
if (conditionNotMet) {
throw new CustomException("Condition not met");
}
Creating Custom Exceptions
Custom exceptions can be created by extending Throwable:
public class CustomException extends Throwable {
public CustomException(String message) {
super(message);
}
}
To use it, you must manually throw an instance of the custom exception.