Junior
How to properly throw exceptions in Java?
sobes.tech AI
Answer from AI
Exceptions should be thrown when an abnormal situation occurs that disrupts the normal execution of the program and requires immediate handling.
Main principles:
- Use exceptions to report errors, not for flow control.
- Choose the most appropriate exception type from the standard library.
- Create custom exception classes when standard ones do not provide sufficient information.
- Include detailed information about the error cause in the exception message, including context.
- Do not catch exceptions that you cannot handle properly. It is better to propagate them up the call stack.
- Use
try-with-resourcesblocks for automatic resource management. - Log exceptions that you handle or propagate to higher levels.
Correct syntax: throw new MyException("Error message");
Example:
// Creating a custom exception
public class InvalidParameterException extends Exception {
public InvalidParameterException(String message) {
super(message);
}
}
// Method that throws an exception
public int divide(int a, int b) throws InvalidParameterException {
if (b == 0) {
throw new InvalidParameterException("Division by zero is not allowed");
}
return a / b;
}
// Using the method and handling the exception
public void performDivision(int x, int y) {
try {
int result = divide(x, y);
System.out.println("Result: " + result);
} catch (InvalidParameterException e) {
// Logging the error
System.err.println("Error during division: " + e.getMessage());
// Possibly further handling or rethrowing
}
}
Differences between Checked and Unchecked exceptions:
| Exception Type | Inherits from | Requires handling/declaration | Example |
|---|---|---|---|
| Checked | Exception (except RuntimeException) |
Yes (try-catch or throws) |
IOException, SQLException |
| Unchecked | RuntimeException |
No (compiler does not require) | NullPointerException, ArrayIndexOutOfBoundsException |