CHAPTER 10 · 2 lessons · 26 exercises

Plan for things going wrong

Keep running when an error happens, and throw an error yourself when a value looks wrong.

So far an error has been "something to fix when it comes out". This chapter changes the view. An error is also something you handle expecting it to happen.

For a program that runs only inside your own computer, an error is a mistyping. But once you start handling data that comes from outside, the story changes. Data arrives in a shape you were not expecting, an entry that should be there is missing, letters sit where numbers should be. It becomes possible for things to fail even when your code is correct.

That is where try and catch come in. Write "the work that might fail" inside the try and "what to do when it failed" in the catch. When an error happens it does not stop there but jumps into the catch. Instead of the whole program falling over, you catch it just at that spot.

What the catch catches is the error that happened itself. Look at message and you can read in words what happened. Show it and chasing the cause later gets easier.

The other one is throw. A way of writing that causes an error yourself. If you know "a negative number as an age is wrong", stopping there is better than carrying the sum on. Let the odd value carry on and it becomes a meaningless result on a line far away, and the cause cannot be traced.

This is also the sequel to "errors are not the enemy" from chapter 1. The sooner you make it fail, the easier the cause is to find. throw is the tool for doing that "make it fail sooner" with your own hands.

What to watch out for is not wrapping everything in a try. Wrap it and the error stops coming out, but what disappeared is the error, not the problem. Do nothing inside the catch and nobody can notice the failure while it carries on running. Wrap only where "you know it can fail and you can decide what to do when it does".

It is a short chapter, but knowing this changes the feel of things once you start building your own app. Think of it as the chapter that takes you from "if it does not work it stops" to "you decide how it behaves when it does not work".

Lessons in this chapter

Catch an error

  1. 88Not stopping at an errorWrite the work that might fail in the try, and what to do when it failed in the catch.Go to the exercises

Throw your own error

  1. 89Throwing an error yourselfTurn an odd value away on the spot with throw, and catch it on the calling side.Go to the exercises

This is the last chapter of the course.