4 Exceptions: Try, Catch, Log
This chapter covers
- A deep dive into Exceptions
- Custom exceptions
- The difference between errors and exceptions
Imagine you’re taking your usual Tuesday evening bath. You’re singing at full volume when suddenly the door opens. Your partner enters with a guest. This was never supposed to happen. It’s an exception in your personal program. If you don’t handle it well, it leads to an awkward situation.
And the same is true in code: If you ignore exceptions, your program may crash or run in an unstable state.
Even if you handle them without logging, you might swallow essential clues. To log exceptions well, you have to understand how they work. That’s why this chapter covers not just logging, but also the fundamentals of exceptions.
4.1 What are exceptions?
While if and else offer control and predictability, exceptions can disrupt the normal flow of a program in unexpected ways. Beginners sometimes avoid them for that reason. Unfortunately, if handled poorly, it is easy to flood the logs with unnecessary information accidentally.
To understand exceptions, we should first take a look at the normal procedural flow of a program. It starts at one point, passes through several steps, and ends in a defined state.
Figure 4.1 Normal program flow