Chapter 8Bugs and Errors

De volgende, grijze tekst hoef je niet te lezen.
Lees verder waar de tekst weer zwart-op-wit wordt.
einde van tekst die overgeslagen kan worden
8.6

Error propagation

Het onderstaande stuk bevat de aanleiding voor het introduceren van Exceptions. Hoewel we dit stuk in de klas hebben behandeld, hoef je dit niet voor de toets te leren.

De volgende, grijze tekst hoef je niet te lezen.
Lees verder waar de tekst weer zwart-op-wit wordt.
einde van tekst die overgeslagen kan worden
8.7

Exceptions

When a function cannot proceed normally, what we would like to do is just stop what we are doing and immediately jump to a place that knows how to handle the problem. This is what exception handling does.

Exceptions are a mechanism that makes it possible for code that runs into a problem to raise (or throw) an exception. An exception can be any value. Raising one somewhat resembles a super-charged return from a function: it jumps out of not just the current function but also its callers, all the way down to the first call that started the current execution. This is called unwinding the stack. You may remember the stack of function calls that was mentioned in Chapter 3. An exception zooms down this stack, throwing away all the call contexts it encounters.

If exceptions always zoomed right down to the bottom of the stack, they would not be of much use. They’d just provide a novel way to blow up your program. Their power lies in the fact that you can set “obstacles” along the stack to catch the exception as it is zooming down. Once you’ve caught an exception, you can do something with it to address the problem and then continue to run the program.

Here’s an example:

function promptDirection(question) {
  let result = prompt(question);
  if (result.toLowerCase() == "left") return "L";
  if (result.toLowerCase() == "right") return "R";
  throw new Error("Invalid direction: " + result);
}

function look() {
  if (promptDirection("Which way?") == "L") {
    return "a house";
  } else {
    return "two angry bears";
  }
}

try {
  console.log("You see", look());
} catch (error) {
  console.log("Something went wrong: " + error);
}

The throw keyword is used to raise an exception. Catching one is done by wrapping a piece of code in a try block, followed by the keyword catch. When the code in the try block causes an exception to be raised, the catch block is evaluated, with the name in parentheses bound to the exception value. After the catch block finishes—or if the try block finishes without problems—the program proceeds beneath the entire try/catch statement.

In this case, we used the Error constructor to create our exception value. This is a standard JavaScript constructor that creates an object with a message property. In most JavaScript environments, instances of this constructor also gather information about the call stack that existed when the exception was created, a so-called stack trace. This information is stored in the stack property and can be helpful when trying to debug a problem: it tells us the function where the problem occurred and which functions made the failing call.

Note that the look function completely ignores the possibility that promptDirection might go wrong. This is the big advantage of exceptions: error-handling code is necessary only at the point where the error occurs and at the point where it is handled. The functions in between can forget all about it.

Je kunt Error inderdaad als een klasse zien met de bijbehorende constructor Error(). Hoewel JavaScript geen klasses kent, kun je klasses wel simuleren en vanaf ES6 heb je daar speciale syntax voor. Dit komt in een volgende les aan bod.

Je kunt in JavaScript elk datatype gooien. Voorbeelden:

//throw new Error('failure');
//throw 'hoi';
//throw 13
//throw {failed: true};
//throw () => {return 'nee dit is echt handig'};

Dit is echter af te raden.

Well, almost...

8.8

Cleaning up after exceptions

Hoewel het stuk hieronder wel nuttig is om te weten, is de hoeveelheid leerstof voor deze week wel voldoende.

De volgende, grijze tekst hoef je niet te lezen.
Lees verder waar de tekst weer zwart-op-wit wordt.
einde van tekst die overgeslagen kan worden
De volgende, grijze tekst hoef je niet te lezen.
Lees verder waar de tekst weer zwart-op-wit wordt.
einde van tekst die overgeslagen kan worden