try…catch…finally

What causes JavaScript Errors ?

There are a few main classes of errors: try…catch…finally

  • Syntax errors : These prevent the relevant code block (within script tags, or included as an external file) from being parsed and compiled. This can be due to mismatched parenthesis or braces, or a misplaced keyword, etc. Syntax errors will prevent that script from running entirely. In the old days, the browser would stop JavaScript execution entirely, but nowadays it just prevents the one script from executing.
  • Type – Error : Raised when the type of a variable is not as expected.
try...catch...finally
  • Run-time errors : These happen during script execution, and typically happen when the code refers to something that doesn’t exist – for instance, calling an undefined function, or referencing a non-existent property of an object or a nonexistent element of an array. Divide by zero or overflow errors are another possibility – or you might run out of stack levels in a function that calls itself (recursion). Though in the last case usually you crash your browser first.
  • Programming errors : Where the code parses and executes, but doesn’t have the expected results. These are the most subtle errors… but the most important: you should spend most of your time on fixing these… Just because the code runs doesn’t mean it’s right!

You’ll notice that JavaScript for the most part doesn’t have type errors when the code expects a string and gets a number, or expects an array and gets an object. Due to implicit typecasting, you get a programming error instead of a run-time error (or in strongly typed languages, a compilation error).

Try :  It allows you to define a block of code to be tested for errors while it is being executed.

try {
    //code here
}

Catch : It allows you to define a block of code to be executed, if an error occurs in the try block.

catch (exception) {
    // code to handle the exception here
}

Finally : lets you execute code, after try and catch, regardless of the result.

try {
   //tryCode - Block of code to try
}
catch(err) {
   //catchCode - Block of code to handle errors
}
finally {
    //finallyCode - Block of code to be executed regardless of the try / catch             result
}

Example:

try {
    alert("I am from try Block");
}
catch ( e ) {
    alert("I am from Catch Block");
}
finally {
     alert("Finally block will always execute!" );
}

Note: The catch and finally statements are both optional, but you need to use one of them (if not both) while using the try statement.

Hint: When an error occurs, JavaScript will normally stop, and generate an error message. Use the throw statement to create a custom error (throw an exception). If you use throw together with try and catch, you can control program flow and generate custom error messages.

Example:

const calculate = (number, callback) => {

    setTimeout(() => {
        if (typeof number !== "number")
            throw new Error("Number is expected");

        const multi = number * number
        callback(multi);
    }, 1000);
}

const callback = result => console.log(result);

try {
    calculate(4, callback);
} catch (e) { console.log(e) }
16

Above code work fine but if you pass the string to the function call

const calculate = (number, callback) => {

    setTimeout(() => {
        if (typeof number !== "number")
            throw new Error("Number is expected");

        const multi = number * number
        callback(multi);
    }, 1000);
}

const callback = result => console.log(result);

try {
    calculate('hello' , callback);
} catch (e) { 
    console.log(e)
}

This indicates that the error has been appropriately handled.

fullstackadda/pointsremember
  1. Try :  It allows you to define a block of code to be tested for errors while it is being executed.
  2. Catch : It allows you to define a block of code to be executed, if an error occurs in the try block.
  3. Finally : lets you execute code, after try and catch, regardless of the result.