DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on

Error handling in javascript

Errors in your code are inevitable. Controlling the flow and error handling are important parts of debugging and making your program run smoothly.

In this post, we'll cover throw, try/catch, and finally.

Throw

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

If you know what your value shouldn't be, you can add a throw statement to your function and catch unapproved values before they continue.

let num = 12

if(num === 12){
  throw "I don't like this value"
}

//expected output: Uncaught I don't like this value

You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying type: strings, numbers, booleans and objects.

Try...Catch

The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it.

The try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block.

let json = '{ "age": 30 }';

try {

  let user = JSON.parse(json); 
  if (!user.name) {
    throw new SyntaxError("Incomplete data: no name");
  }

  console.log( user.name );

} catch(e) {
  console.log( "JSON Error: " + e ); 
}

When we obtain our JSON object, we find there is no name property. Now we throw our new Syntax error, which means that our catch block will run and log the error in the console. If there was a name in the JSON, it would log the name.

Finally

The finally block contains statements to be executed after the try and catch blocks execute. Additionally, the finally block executes before the code that follows the try…catch…finally statement.

It is also important to note that the finally block will execute whether or not an exception is thrown. If an exception is thrown, however, the statements in the finally block execute even if no catch block handles the exception that was thrown.

try {

  let user = JSON.parse(json); 
  if (!user.name) {
    throw new SyntaxError("Incomplete data: no name");
  }

  console.log( user.name );

} catch(e) {
  console.log( "JSON Error: " + e ); 
} finally {
  console.log("This will always run, even when there's no exception")
}

Top comments (1)

Collapse
 
viniciusrio profile image
Vinicius Rio

Thanks, its is very simple and useful!