Skip to Content
Speaking JavaScript
book

Speaking JavaScript

by Axel Rauschmayer
February 2014
Beginner to intermediate content levelBeginner to intermediate
460 pages
8h 32m
English
O'Reilly Media, Inc.
Content preview from Speaking JavaScript

Chapter 14. Exception Handling

This chapter describes how JavaScript’s exception handling works. It begins with a general explanation of what exception handling is.

What Is Exception Handling?

In exception handling, you often group statements that are tightly coupled. If, while you are executing those statements, one of them causes an error, then it makes no sense to continue with the remaining statements. Instead, you try to recover from the error as gracefully as you can. This is loosely reminiscent of transactions (but without the atomicity).

Let’s look at code without exception handling:

function processFiles() {
    var fileNames = collectFileNames();
    var entries = extractAllEntries(fileNames);
    processEntries(entries);
}
function extractAllEntries(fileNames) {
    var allEntries = new Entries();
    fileNames.forEach(function (fileName) {
        var entry = extractOneEntry(fileName);
        allEntries.add(entry);  // (1)
    });
}
function extractOneEntry(fileName) {
    var file = openFile(fileName);  // (2)
    ...
}
...

What is the best way to react to an error in openFile() at (2)? Clearly, the statement (1) should not be executed anymore. But we wouldn’t want to abort extractAllEntries(), either. Instead, it is enough to skip the current file and continue with the next one. To do that, we add exception handling to the previous code:

function extractAllEntries(fileNames) {
    var allEntries = new Entries();
    fileNames.forEach(function (fileName) {
        try {
            var entry = extractOneEntry(fileName);
            allEntries.add(entry);
        } 
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Joy of JavaScript

The Joy of JavaScript

Luis Atencio
Secrets of the JavaScript Ninja, Second Edition

Secrets of the JavaScript Ninja, Second Edition

Bear Bibeault, Josip Maras, John Resig

Publisher Resources

ISBN: 9781449365028Errata