JS: Throw Try Catch Finally

By Xah Lee. Date: . Last updated: .

JavaScript has the following keywords for handling errors: throw and {try, catch, finally}.

They are flow control for dealing with errors, called “exception handling”.

Here's a typical usage syntax:

try {
    // call a function that might throw.
    // or throw yourself here
    if ( something ) {
        throw "XYZ";
    }
}
catch (abc) {
    // abc is a parameter. its value is from throw
    console.log (abc); // prints XYZ
}
finally {
    console.log ("Finally block run!");
}

How to Use “throw”, “try/catch/finally”

The syntax of “throw” is:

  • throw expr;
  • The syntax of “try/catch/finally” is any of the following:

    When the “throw” statement is run, it redirect code execution to a outer “catch” block of a “try/catch/finally” statement. Then, run the “finally” block if there's one.

    If no “try/catch/finally” is found, JavaScript stops running and prints the expression passed by “throw”.

    “throw” is the most important in “throw/try/catch/finally”. Without “throw”, the “try/catch/finally” is useless.

    The purpose of “try” block is just to contain “throw” (or contain function calls that may “throw”.).

    When the “try/catch/finally” is run, code in the “try” block is executed. If throw happens in “try” block, the “catch” block is run, else skipped. The “finally” block (if any) is always run.

    try {
        console.log (3);
    } catch(e) {
        console.log (4);
    }
    finally {
        console.log (5);
    }
    
    // result:
    // prints 3 5

    The “throw” and “try/catch/finally” block can be used without each other. But, typically, “throw” is used inside a “try” block. And you should do so in your code.

    「throw」 Statement

    throw is like goto. It moves the execution to another place in code. The syntax is this:

    throw expression;

    // example of throw in a function, caught outside of the function
    
    function ff () {
        throw 4;
    }
    
    try {
        ff();
    } catch(ee) {
        console.log (ee);
    };

    When “throw” is called, execution jumps to the nearest outer block of catch in a “try/catch/finally” block. If the nearest outer block is a function block, then JavaScript tries to find the outer “catch” at where the function is called.

    It repeats the process of jumping to the nearest outer block to find a “try/catch/finally”.

    If no “try/catch/finally” is found, it's a error, JavaScript stops running and argument of “throw” is printed.

    If a “try/catch/finally” is found, the program flow continues at the “catch” block, and the argument of “throw” is passed to the parameter of “catch”.

    // throw can be run by itself
    throw 3;
    
    // this is un-catched throw.
    // js exits and prints 3
    // throw in a try/catch block
    
    try {
        throw 3;
    } catch(e) {
        console.log (e);
    }
    
    // exits normally.
    // result is printing 3
    // throw in a try/catch block
    
    try {
        if ( false ) {
            throw 3;
        };
    } catch(e) {
        console.log (e);
    }
    
    // throw is never executed

    “try” Statement

    The try statement encloses a block of code in which an exceptional condition can occur, such as a runtime error or a throw statement. The catch clause provides the exception-handling code. When a catch clause catches an exception, its CatchParameter is bound to that exception.

    ECMAScript 5.1 §12#sec-12.14

    ECMAScript 2015 §Error Handling and Language Extensions#sec-error-handling-and-language-extensions

    Here's a example of “try”, trying to call a function that may not exist.

    try {
        yyy();
    } catch(e) {
        console.log ("aa");
    }
    
    console.log ("bb");
    
    // result is printing aa then bb
    
    // without the try block, calling a non-existent function will exit abnormally, and bb won't be printed

    Error Object

    The throw is often used with a error object. That is, in throw expr;, the expr is a error object.

    // throw an error object
    
    try {
        throw new Error("xyz is wrong.");
    } catch(ee) {
        console.log (ee);
    };

    However, Error object in JavaScript is independent of the “throw/try/catch” statement.

    See: Javascript: Error Object.

    JavaScript Basics

    1. JavaScript Basics
    2. Operators
    3. true, false
    4. Branch Control
    5. Loop
    6. Array Basics
    7. Object Basics

    Value Types

    1. Value Types
    2. Primitive Value
    3. “typeof” Operator

    Variable

    1. let
    2. const
    3. var 👎
    4. var Order 👎
    5. var Scope 👎
    6. Global Variable
    7. Destructuring Assignment

    String

    1. String Overview
    2. Template String
    3. String Escape Sequence
    4. Unicode Escape Sequence
    5. Char, Code Unit, Codepoint

    Function

    1. Define Function
    2. Arrow Function ⭐
    3. Function Params
    4. “arguments” Object
    5. Rest Params ⭐
    6. Arg Default Value ⭐
    7. Arg Destructure ⭐
    8. f Declaration vs Expression
    9. Closure
    10. f call apply bind
    11. Functional Programing

    Object Property

    1. Property Overview
    2. Property Key
    3. Dot vs Bracket Notation
    4. Create/Delete Property
    5. Get/Set Property
    6. Property Existence
    7. Access Property
    8. List Properties
    9. Property Attributes
    10. Getter/Setter
    11. Property Descriptor
    12. Symbol

    Object and Inheritance

    1. Object Overview
    2. Object Type
    3. Find Object's Type
    4. Prototype Chain
    5. Check is in Prototype Chain
    6. Get/Set Parent
    7. Show Prototype Chain
    8. Create Object
    9. Object Literal Expr
    10. Create Object with Parent X
    11. Prevent Adding Property
    12. Clone Object
    13. Test Object Equality
    14. Add Method to Prototype

    Array

    1. Understand JS Array
    2. Create Array
    3. Sparse Array
    4. Array-Like Object
    5. Array How-To

    Constructor/Class

    1. “this” Binding
    2. What's Constructor?
    3. Property Key "prototype"
    4. Operator “new”
    5. Operator “instanceof”
    6. Property Key “constructor”
    7. Class
    8. Keyword “extends”
    9. Keyword “super”

    Iterable ⭐

    1. Interface
    2. Iterable
    3. Iterator
    4. Iterator Prototype
    5. for-of Loop
    6. Spread Operator
    7. Generator
    8. Generator Function

    Regular Expression

    1. RegExp Basics
    2. RegExp Syntax
    3. Regex Find/Replace

    Date

    1. Date Tutorial
    2. Compute Date Range

    Set Object

    1. Set Object
    2. Union, Intersection, Diff

    Map Object

    1. Map Object
    2. Iterate Over Map Object
    3. Convert Object to/from Map
    4. Map Filter
    5. Reverse Key/Value

    Number

    1. String to/from Number
    2. Convert Decimal/Hexadecimal
    3. Format Number
    4. Random Number

    Misc

    1. Import/Export
    2. Promise
    3. Proxy
    4. Try Catch Throw Finally
    5. ES2015 Features
    6. ES2016, 2017, 2018, 2019
    7. How to Convert ES5 to ES2015
    8. Style Guide
    9. Semicolon Rules
    10. Exclamation Before Function
    11. How to Determine Strict Mode?
    12. x.y.z Associativity
    13. Function Chain
    14. Random Number, Range, Integer, Element
    15. Timing JS Code
    16. Range Function for Array
    17. Tagged Template String
    18. Allowed Characters in Identifier
    19. Encode URL, Escape String

    Object Reference

    If you have a question, put $5 at patreon and message me.

    Web Dev Tutorials