There are two ways to write error-free programs; only the third works.

Alan J. Perlis

Chapter 5
Prepare for Things Going Wrong

Do you own a car? Do you have insurance for it? If not, you’d better get a policy now. It can cost you a lot of money, and chances are, you’ll drive your car for thousands of miles without any trouble. But it just takes a moment of bad luck to leave you with life-changing consequences. That’s why you need insurance to act as a safety net for your really expensive things (cars, houses) and your really important things (your health!).

It’s similar with code. Most of the time, your program will execute just fine and take the happy path (the default control-flow path without any exceptional or erroneous conditions). But things can and will go wrong. When they do, you’ll need a safety net. If you don’t have one, your program could suffer the consequences—it can crash or produce faulty data. Or worst of all, it can continue to run as if nothing happened—you won’t see the damage until much later, and by then, you’ll have a hard time figuring out what’s wrong (not to mention all the data that might have been corrupted by then).

You have to ensure your program against errors even if it’s completely bug-free (and it never is). That’s because there are things that you just can’t control. For example, a user might try to read a file from a broken filesystem. Or the machine where your program is running might be disconnected from the network. Or it might receive malicious messages from a remote host.

In Java, we ensure our program handle errors by catching and throwing exceptions. The comparisons we’ll explore in this chapter will show you several important do’s and don’ts related to handling exceptions. You will learn how to fail fast while collecting as much information about the error as possible (without breaking the exception cause chain) and be explicit about swallowing errors. When handling exceptions, your program will leave the normal path of executions. That’s why you need to be sure you always close your scarce resources. Remember: It’s better to be safe than sorry! Let’s begin.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.76.204