Sub topic 17
Exception Handling Best Practices
You now know the tools: try, catch, finally, throw, throws, custom exceptions, chaining, and try-with-resources. This chapter covers how to use them well. A best practice is a habit that most experienced developers agree makes code safer and easier to fix. Each practice below comes with a short reason and an example.
Catch Specific Types
Catch the exact exception you expect, such as NumberFormatException or IOException. Avoid catching the general Exception class unless you have a strong reason.
A broad catch also traps problems you did not plan for, like a NullPointerException caused by a bug. Your code then treats a bug as if it were bad user input, and the real cause stays hidden.
public class SpecificCatch {
public static void main(String[] args) {
String text = "12a";
try {
int n = Integer.parseInt(text);
System.out.println("Parsed: " + n);
} catch (NumberFormatException e) {
System.out.println("Please enter digits only, got: " + text);
}
}
}Only the expected failure gets the friendly message. Any other exception keeps moving up the call stack, where someone can see it.
Never Swallow an Exception Silently
To swallow an exception is to catch it and do nothing. This is the most harmful habit in exception handling.
try {
int n = Integer.parseInt(text);
} catch (NumberFormatException e) {
// nothing here
}The program goes on as if nothing went wrong. Later, something else fails, and you have no clue where it started. Every catch block should do at least one of these things:
- Recover: fix the situation, for example by using a default value and saying so.
- Report: log the problem or show a clear message.
- Rethrow: pass it on, often wrapped in a more meaningful exception.
If you are sure that ignoring an exception is correct, write a comment that explains why. Then the next reader knows you made the choice on purpose.
Don't Use Exceptions for Normal Flow
Exceptions are for unusual events. Creating one is slow compared to an if check, because Java records the stack trace. Code that throws exceptions as part of its normal work is also hard to read.
If you can check a condition in advance, check it:
public class CheckFirst {
public static void main(String[] args) {
int[] scores = {90, 75, 60};
int index = 5;
if (index >= 0 && index < scores.length) {
System.out.println("Score: " + scores[index]);
} else {
System.out.println("No score at position " + index);
}
}
}This is better than reading scores[5] and catching ArrayIndexOutOfBoundsException.
Throw Early, Catch Late
Throw early means checking inputs at the start of a method and throwing right away if they are invalid. The stack trace then points close to the real mistake.
Catch late means catching an exception only where you can do something useful with it. A low-level method that reads a file usually cannot decide what to tell the user. The code near the top of the program, such as main, can.
Keep the Cause When You Wrap
When you turn a low-level exception into your own exception, pass the original exception as the cause. If you drop it, the stack trace loses the most useful part.
// Bad: the original IOException is lost
throw new ConfigException("cannot read config");
// Good: the IOException is kept as the cause
throw new ConfigException("cannot read config", e);Write Helpful Messages
An exception message should say what failed and include the values involved. "Error" tells you nothing. "Port is not a number in config/port.txt" tells you where to look.
Keep secrets out of messages. Passwords, tokens, and private user data should never appear in an exception message, because messages often end up in log files.
Close Resources with try-with-resources
Use try-with-resources for anything that implements AutoCloseable, such as files, streams, and database connections. It closes them in every case and keeps errors from close() as suppressed exceptions. A hand-written finally block is longer and easier to get wrong.
Also, never put return inside a finally block. A return there throws away any exception that the try block threw, so the failure disappears without a trace.
Putting It All Together
This program reads a port number from a file. It uses several practices at once: specific catches, try-with-resources, a custom checked exception, kept causes, clear messages, and one place near the top that reports the problem.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigLoader {
static int readPort(Path path) throws ConfigException {
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line = reader.readLine();
if (line == null) {
throw new ConfigException("config file is empty: " + path);
}
return Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
throw new ConfigException("port is not a number in " + path, e);
} catch (IOException e) {
throw new ConfigException("cannot read " + path, e);
}
}
public static void main(String[] args) {
Path path = Path.of(args.length > 0 ? args[0] : "port.txt");
try {
int port = readPort(path);
System.out.println("Port: " + port);
} catch (ConfigException e) {
System.err.println("Startup failed: " + e.getMessage());
e.printStackTrace();
}
}
}
class ConfigException extends Exception {
ConfigException(String message) {
super(message);
}
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}Save it as ConfigLoader.java, then run javac ConfigLoader.java and java ConfigLoader. Try it three ways:
- With no
port.txtfile. You get "cannot read port.txt", and the stack trace shows aNoSuchFileExceptionunder "Caused by". - With
port.txtcontainingabc. You get "port is not a number", with theNumberFormatExceptionas the cause. - With
port.txtcontaining8080. The program printsPort: 8080.
The ConfigException thrown for an empty file is not caught by the two catch clauses inside readPort, because it is neither a NumberFormatException nor an IOException. It goes straight to main.
Quick Reference
| Practice | Why it helps |
|---|---|
| Catch specific types | Bugs are not mistaken for expected failures |
| Never swallow exceptions | Problems stay visible |
| Use `if` checks for normal cases | Code is faster and clearer |
| Throw early, catch late | Errors are found near their source and handled where it makes sense |
| Keep the cause when wrapping | The full story stays in the stack trace |
| Write clear messages without secrets | Problems are faster to fix and logs stay safe |
| Use try-with-resources | Resources always close |
| No `return` in `finally` | Exceptions are not thrown away |
Exercise
A teammate writes catch (Exception e) { } around a call to Integer.parseInt(input). Name two problems with this code and describe a better version.
Show answer
First, it catches every exception, so bugs such as a NullPointerException are hidden along with bad input. Second, the empty block swallows the exception, so nobody learns that anything failed. A better version catches only NumberFormatException and reports it, for example by printing "Please enter digits only" or by using a default value and logging that it did.
Exercise
In ConfigLoader, what would you lose if the IOException catch block were changed to throw new ConfigException("cannot read " + path);?
Show answer
You would lose the original IOException as the cause. The stack trace would no longer show a "Caused by" section, so you could not tell whether the file was missing, locked, or unreadable for some other reason.
Exercise
Why is it a bad idea to write return 0; inside a finally block?
Show answer
A return in finally replaces whatever the try or catch block was doing, including any exception being thrown. The exception is thrown away without a trace, which is a form of silent swallowing.