Search code examples
javascriptexceptionerror-handlingruntime-error

Errors vs Exceptions in JS - Are there exceptions in JavaScript?


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

Error

Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.

Description

Runtime errors result in new Error objects being created and thrown.

According to MDN, can we say that Errors are the same as Exceptions because both are created with the Error class, or is there an Exception class in JavaScript?


Solution

  • The JavaScript exception mechanism consists of the throw statement:

    throw expression;
    

    Any value, any value at all, can be thrown. The other part is the try catch structure:

    try {
      arbitrary code
    }
    catch (value) {
      handler code for thrown value
    }
    

    The thing about try and catch is that it handles exceptions thrown by arbitrary levels of function calls within the try block, like most other languages with that feature.

    The catch (value) clause is not typed, as it is in (for example) Java. Thus unlike Java multiple catch blocks for a single try doesn't make sense.

    The Error built-in constructor is a standardized facility for creating objects to throw with commonly-useful features. There are also several subclasses of Error for different situations (see the MDN documentation) though for application code they're probably not terribly useful; however, they're available. In some runtimes, Error instances have access to detailed information about the context of the point in the code at which they were created, such as source code line number and stack information. That makes

    if (somethingBad) throw new Error("Something bad");
    

    more useful. However, that context information is not available in all JavaScript runtimes.

    Of course with modern class declarations it's possible to subclass Error if that seems useful. Personally, if I have an application that makes me feel like custom Error subclasses are important, I might take a step back and wonder why I have so many different throw situations. Throwing exceptions is expensive, and in most runtimes a try catch structure in a function will mean that very little optimization can be done because the optimizer has no clue what might happen. Thus, and this is true of all languages with a similar feature, try catch and throw should usually not be used as part of basic program logic. It really should be about "exceptional" situations, things that shouldn't happen but nevertheless do happen sometimes.