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!

The JavaScript Brief

Dive into the world of JavaScript with these three trendworthy articles that you cannot miss this week!

7 JavaScript Web APIs to build Futuristic Websites you didn't know

Explore the world of overlooked Web APIs that can bring your next project to new heights 🌕🚀. Some of the best Web APIs include Screen Capture API, Clipboard API and Web Workers API. Get informed and cast a glance at some of the future stars of web development.

10 GitHub Repositories You Should Know as a JavaScript Developer

Elevate your skills as a JavaScript developer with these 10 top GitHub repositories. Ranging from NodeJS best practices to diverse libraries and collections, these repositories are a must-know for any dedicated JS dev.

20 Killer JavaScript One-Liners That’ll Save You Hours of Coding

Multiply your coding agility with 20 essential JavaScript one-liners 🚀 that save both time and energy when developing. Discover amazing one-liners for finding max value in an array, capitalizing the first letter of a phrase, generate secure ID, among many others.

Get inspired, and level up your JavaScript game with this week's top reads! 🎢🧗