Java Exception Handling
In Java, you can throw errors (exceptions) in several ways:
Using the
throwkeyword: You can manually throw an exception using thethrowkeyword. Typically, you need to create an exception object (like a subclass ofRuntimeException) and pass it to thethrowkeyword. For example:1
throw new RuntimeException("This is a custom exception message");
Using predefined exception classes: Java has many built-in exception classes that you can use to throw exceptions as needed. For example:
1
2throw new NullPointerException("Object is null, cannot perform the operation");
throw new IOException("An I/O exception occurred");Custom exception classes: You can create your custom exception classes, typically inheriting from
Exceptionor its subclasses, to represent specific error conditions.1
2
3
4
5
6
7
8public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// Throwing a custom exception
throw new CustomException("Custom exception message");Using the
throwskeyword: In the method signature, you can use thethrowskeyword to declare that the method may throw an exception. This informs the caller that the method might raise a specific type of exception. The caller must handle the exception or propagate it to the next level.1
2
3
4
5
6
7public void someMethod() throws IOException {
// ...
if (someCondition) {
throw new IOException("I/O exception");
}
// ...
}Exception chaining: After catching an exception, you can wrap it in another exception and throw it, thus creating an exception chain. This is often used to throw higher-level exceptions without losing the original exception information. For example:
1
2
3
4
5try {
// ...
} catch (IOException e) {
throw new CustomException("An exception occurred while processing the file", e);
}Here, the
CustomExceptionincludes the originalIOExceptionto aid in debugging and problem resolution.
Example of Handling Exceptions
Here is a comprehensive example demonstrating the different ways to throw and handle exceptions in Java:
1 | // Custom Exception Class |
In this example:
- A
CustomExceptionclass is defined. - The
methodThatThrowsmethod declares that it may throw bothIOExceptionandCustomException. - The
riskyMethodmethod throws anIOException. - The
methodThatThrowsmethod catches theIOExceptionand wraps it in aCustomExceptionbefore throwing it. - The
mainmethod handles bothIOExceptionandCustomException, demonstrating how to catch and process multiple exceptions.