Ch 7. Error handling
- Things can go wrong, and when they do, we as programmers are responsible for making sure that our code does what it needs to do.
- It is nearly impossible to see what the code does because of all of the scattered error handling.
- Error handling is important, but if it obscures logic, it’s wrong.
Use Exceptions Rather Than Return Codes
public void sendShutDown() {
DeviceHandle handle = getHandle(DEV1);
// Check the state of the device
if (handle != DeviceHandle.INVALID) {
// Save the device status to the record field
retrieveDeviceRecord(handle);
// If not suspended, shut down
if (record.getStatus() != DEVICE_SUSPENDED) {
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
} else {
logger.log("Device suspended. Unable to shut down");
}
} else {
logger.log("Invalid handle for: " + DEV1.toString());
}
}- You either set an error flag or returned an error code that the caller could check. The problem with these approaches is that they clutter the caller.
- The caller must check for errors immediately after the call. Unfortunately, it’s easy to forget. For this reason it is better to throw an exception when you encounter an error.
public void sendShutDown() {
try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}
}
private void tryToShutDown() throws DeviceShutDownError {
DeviceHandle handle = getHandle(DEV1);
DeviceRecord record = retrieveDeviceRecord(handle);
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
}- The calling code is cleaner. Its logic is not obscured by error handling. This isn’t just a matter of aesthetics.
- The code is better because two concerns that were tangled, the algorithm and error handling, are now separated.
Write Your Try-Catch-Finally Statement First
- One of the most interesting things about exceptions is that they define a scope within your program. When you execute code in the try portion of a try-catch-finally statement, you are stating that execution can abort at any point and then resume at the catch.
- In a way, try blocks are like transactions. Your catch has to leave your program in a consistent state, no matter what happens in the try.
- For this reason it is good practice to start with a try-catch-finally statement when you are writing code that could throw exceptions. This helps you define what the user of that code should expect, no matter what goes wrong with the code that is executed in the try.
- Try to write tests that force exceptions, and then add behavior to your handler to satisfy your tests. This will cause you to build the transaction scope of the try block first and will help you maintain the transaction nature of that scope.
Provide Context with Exceptions
- Each exception that you throw should provide enough context to determine the source and location of an error.
- Create informative error messages and pass them along with your exceptions. Mention the operation that failed and the type of failure.
- If you are logging in your application, pass along enough information to be able to log the error in your catch.
Define Exception Classes in Terms of a Caller’s Needs
- When we define exception classes in an application, our most important concern should be how they are caught.
ACMEPort port = new ACMEPort(12);
try {
port.open();
} catch (DeviceResponseException e) {
reportPortError(e);
logger.log("Device response exception", e);
} catch (ATM1212UnlockedException e) {
reportPortError(e);
logger.log("Unlock exception", e);
} catch (GMXError e) {
reportPortError(e);
logger.log("Device response exception");
} finally {
…
}v.s.
public class LocalPort {
private ACMEPort innerPort;
public LocalPort(int portNumber) {
innerPort = new ACMEPort(portNumber);
}
public void open() {
try {
innerPort.open();
} catch (DeviceResponseException e) {
throw new PortDeviceFailure(e);
} catch (ATM1212UnlockedException e) {
throw new PortDeviceFailure(e);
} catch (GMXError e) {
throw new PortDeviceFailure(e);
}
}
…
}
LocalPort port = new LocalPort(12);
try {
port.open();
} catch (PortDeviceFailure e) {
reportError(e);
logger.log(e.getMessage(), e);
} finally {
…
}- Wrappers like the one we defined for ACMEPort can be very useful. In fact, wrapping third-party APIs is a best practice.
- When you wrap a third-party API, you minimize your dependencies upon it: You can choose to move to a different library in the future without much penalty.
- Wrapping also makes it easier to mock out third-party calls when you are testing your own code.
- One final advantage of wrapping is that you aren’t tied to a particular vendor’s API design choices. You can define an API that you feel comfortable with.
- In the preceding example, we defined a single exception type for port device failure and found that we could write much cleaner code.
- Often a single exception class is fine for a particular area of code. The information sent with the exception can distinguish the errors.
- Use different classes only if there are times when you want to catch one exception and allow the other one to pass through.
Define the Normal Flow
- The process of doing this pushes error detection to the edges of your program. You wrap external APIs so that you can throw your own exceptions, and you define a handler above your code so that you can deal with any aborted computation. Most of the time this is a great approach, but there are some times when you may not want to abort.
try {
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
} catch (MealExpensesNotFound e) {
m_total += getMealPerDiem();
}
- In this business, if meals are expensed, they become part of the total. If they aren’t, the employee gets a meal per diem amount for that day. The exception clutters the logic.
- Wouldn’t it be better if we didn’t have to deal with the special case? If we didn’t, our code would look much simpler. It would look like this:
- Can we make the code that simple? It turns out that we can. We can change the expenseReportDAO so that it always returns a MealExpense object. If there are no meal expenses, it returns a MealExpense object that returns the per diem as its total
public class PerDiemMealExpenses implements MealExpenses {
public int getTotal() {
// return the per diem default
}
}- This is called the SPECIAL CASE PATTERN [Fowler]. You create a class or configure an object so that it handles a special case for you. When you do, the client code doesn’t have to deal with exceptional behavior. That behavior is encapsulated in the special case object.
Sure, I can help you re-format this text into Markdown for better readability:
# Define the Normal Flow
- The process of doing this pushes error detection to the edges of your program. You wrap external APIs so that you can throw your own exceptions, and you define a handler above your code so that you can deal with any aborted computation. Most of the time this is a great approach, but there are some times when you may not want to abort.
```cpp
try {
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
} catch (MealExpensesNotFound e) {
m_total += getMealPerDiem();
}- In this business, if meals are expensed, they become part of the total. If they aren’t, the employee gets a meal per diem amount for that day. The exception clutters the logic.
- Wouldn’t it be better if we didn’t have to deal with the special case? If we didn’t, our code would look much simpler. It would look like this:
- Can we make the code that simple? It turns out that we can. We can change the
expenseReportDAOso that it always returns aMealExpenseobject. If there are no meal expenses, it returns aMealExpenseobject that returns the per diem as its total.
public class PerDiemMealExpenses implements MealExpenses {
public int getTotal() {
// return the per diem default
}
}- This is called the SPECIAL CASE PATTERN [Fowler]. You create a class or configure an object so that it handles a special case for you. When you do, the client code doesn’t have to deal with exceptional behavior. That behavior is encapsulated in the special case object.
Don’t Return Null
- I think that any discussion about error handling should include mention of the things we do that invite errors. The first on the list is returning null.
public void registerItem(Item item) {
if (item != null) {
ItemRegistry registry = persistentStore.getItemRegistry();
if (registry != null) {
Item existing = registry.getItem(item.getID());
if (existing.getBillingPeriod().hasRetailOwner()) {
existing.register(item);
}
}
}
}-
If you work in a code base with code like this, it might not look all that bad to you, but it is bad! When we return null, we are essentially creating work for ourselves and foisting problems upon our callers. All it takes is one missing null check to send an application spinning out of control.
- Did you notice the fact that there wasn’t a null check in the second line of that nested if statement? What would have happened at runtime if
persistentStorewere null? We would have had aNullPointerExceptionat runtime, and either someone is catchingNullPointerExceptionat the top level or they are not. Either way, it’s bad. - What exactly should you do in response to a
NullPointerExceptionthrown from the depths of your application? It’s easy to say that the problem with the code above is that it is missing a null check, but in actuality, the problem is that it has too many.
- Did you notice the fact that there wasn’t a null check in the second line of that nested if statement? What would have happened at runtime if
-
If you are tempted to return null from a method, consider throwing an exception or returning a SPECIAL CASE object instead.
-
If you are calling a null-returning method from a third-party API, consider wrapping that method with a method that either throws an exception or returns a special case object.
-
In many cases, special case objects are an easy remedy. Imagine that you have code like this:
List<Employee> employees = getEmployees();
if (employees != null) {
for (Employee e : employees) {
totalPay += e.getPay();
}
}- Right now,
getEmployeescan return null, but does it have to? If we changegetEmployeeso that it returns an empty list, we can clean up the code:
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}- Fortunately, Java has
Collections.emptyList(), and it returns a predefined immutable list that we can use for this purpose:
public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}- If you code this way, you will minimize the chance of
NullPointerExceptions, and your code will be cleaner.
Don’t Pass Null
- Returning null from methods is bad, but passing null into methods is worse.
- Unless you are working with an API that expects you to pass null, you should avoid passing null in your code whenever possible.
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x – p1.x) * 1.5;
}
...
}- What happens when someone passes null as an argument?
calculator.xProjection(null, new Point(12, 13));- We’ll get a
NullPointerException, of course. - How can we fix it? We could create a new exception type and throw it:
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw new InvalidArgumentException("Invalid argument for MetricsCalculator.xProjection");
}
return (p2.x – p1.x) * 1.5;
}
}- Is this better? It might be a little better than a null pointer exception, but remember, we have to define a handler for
InvalidArgumentException. What should the handler do? Is there any good course of action? - There is another alternative. We could use a set of assertions:
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x – p1.x) * 1.5;
}
}- It’s good documentation, but it doesn’t solve the problem. If someone passes null, we’ll still have a runtime error.
- In most programming languages, there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default. When you do, you can code with the knowledge that a null in an argument list is an indication of a problem, and end up with far fewer careless mistakes.
Conclusion
- Clean code is readable, but it must also be robust. These are not conflicting goals.
- We can write robust clean code if we see error handling as a separate concern, something that is viewable independently of our main logic. To the degree that we are able to do that, we can reason about it independently, and we can make great strides in the maintainability of our code.