What are the best practices for exception handling in Java?
- Catch specific exceptions, not just
ExceptionorThrowable. - Never swallow an exception with an empty
catch. At least log it. - Use try with resources to close files, sockets and connections.
- Keep the cause when you wrap an exception:
throw new MyException("message", e). - Add useful details to the message: which value, which file.
- Do not use exceptions for normal flow, like ending a loop. They are slow and unclear.
- Throw early, catch late: check arguments at the start, and handle the error where you can do something about it.
- Use unchecked exceptions for programming errors, and checked ones only when the caller can recover.
public class Main {
static class ConfigException extends RuntimeException {
ConfigException(String message, Throwable cause) { super(message, cause); }
}
static int readPort(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new ConfigException("Invalid port value '" + text + "'", e); // keeps the cause
}
}
public static void main(String[] args) {
try {
readPort("80x");
} catch (ConfigException e) {
System.out.println(e.getMessage());
System.out.println("Cause: " + e.getCause());
}
}
}
Output
Invalid port value '80x'
Cause: java.lang.NumberFormatException: For input string: "80x"
See Java Exceptions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |