Skip to main content

JavaScript Try Catch

JavaScript try and catch are used together to handle errors that may occur in a block of code.

The try block is used to enclose the code that might throw an error. If an error occurs in the try block, JavaScript stops executing the code and jumps directly to the catch block.

The catch block is used to catch the error and handle it. It takes an argument, which is the error object that describes the error that occurred. You can use this object to get more information about the error and take appropriate actions to handle it.

As an example:

try {
// code that might throw an error
let x = y + 1;
} catch (error) {
// code to handle the error
console.log("An error occurred: " + error.message);
}

In this example:

  • If y is not defined, JavaScript will throw an error when trying to execute let x = y + 1;.
  • The catch block will catch the error and log a message that describes the error to the console.
tip

try and catch only catch errors that occur in the same execution context. If an error occurs in a function that's called from the try block, you'll need to use another try and catch block to handle that error.

The throw Statement

The throw statement in JavaScript is used to throw a user-defined exception. When an exception is thrown, the JavaScript interpreter stops executing the current function and looks for a matching catch block to handle the exception.

The syntax for throw statement is as shown below:

throw expression;

Here:

  • The expression can be any valid JavaScript expression that returns a value.
  • When the throw statement is executed, the expression is evaluated and the resulting value is thrown as an exception.

As an example:

function divide(num1, num2) {
if (num2 === 0) {
throw "Divide by zero error!";
}
return num1 / num2;
}

try {
console.log(divide(10, 0));
} catch (error) {
console.log("Error: " + error);
}

In this example:

  • The divide function checks if the num2 parameter is zero. If it is, the function throws an exception with the message "Divide by zero error!".
  • When the divide function is called with the parameters 10 and 0, the exception is thrown and caught by the catch block, which logs the error message to the console.

The finally Statement

The finally statement in JavaScript is used to define a block of code that will be executed regardless of whether an exception is thrown or caught. The finally block is optional and is typically used to perform clean-up tasks or release resources.

The syntax for finally statement is as shown below:

try {
// code that might throw an exception
} catch (error) {
// code to handle the exception
} finally {
// code to be executed regardless of whether an exception is thrown or caught
}

Here:

  • The try block is used to enclose the code that might throw an exception.
  • If an exception is thrown, the catch block is used to handle the exception.
  • The finally block is used to define the code that will be executed regardless of whether an exception is thrown or caught.

As an example:

let file = null;

try {
file = openFile("filename");
// code to read the file
} catch (error) {
console.log("Error reading file: " + error);
} finally {
if (file !== null) {
closeFile(file);
}
}

In this example:

  • The try block is used to open a file and read its contents. If an exception is thrown.
  • The catch block is used to handle the exception and log an error message to the console.
  • The finally block is used to close the file, regardless of whether an exception is thrown or not.

The Error Object

The Error object in JavaScript is a built-in object that provides information about an error that occurred in a block of code. It contains properties that describe the error, such as the error message, the line number where the error occurred, and the name of the error.

As an example:

try {
// code that might throw an error
let x = y + 1;
} catch (error) {
// code to handle the error
console.log("An error occurred: " + error.message);
console.log("Error name: " + error.name);
console.log("Error stack trace: " + error.stack);
console.log("Line number: " + error.lineNumber);
}

In this example:

  • If y is not defined, JavaScript will throw a ReferenceError with the message "y is not defined".
  • The catch block will catch the error and log the error message, the name of the error ("ReferenceError"), the stack trace (which shows the function call stack at the time of the error), and the line number where the error occurred.

The Error object has several built-in properties, including:

  • message: A string that describes the error.
  • name: A string that specifies the name of the error.
  • stack: A string that contains a stack trace of the error.
  • lineNumber: A number that specifies the line number where the error occurred.
  • fileName: A string that specifies the name of the file where the error occurred.
tip

You can also create your own custom Error objects by extending the Error class. This allows you to create custom error messages and error types for your own applications.

Error Name Values

There are several error name values that can be thrown in JavaScript, each representing a different type of error.

Here are some of the most common error name values:

  • Error: The base Error class represents generic errors. It can be used as a catch-all for any error that does not fit into a more specific category.

  • TypeError: This error is thrown when a variable or parameter is not of the expected type. For example, trying to call a method on a null value will throw a TypeError.

  • SyntaxError: This error is thrown when there is a problem with the syntax of the code. For example, forgetting a closing bracket or using an invalid character will result in a SyntaxError.

  • ReferenceError: This error is thrown when a variable or function cannot be found. For example, trying to access an undefined variable will result in a ReferenceError.

  • RangeError: This error is thrown when a value is not within a specified range. For example, trying to create an array with a length that is not a positive integer will result in a RangeError.

  • EvalError: This error is thrown when there is a problem with the eval() function. This error is rarely used in modern JavaScript and is typically only thrown in older versions of the language.

  • URIError: This error is thrown when there is a problem with a URI (Uniform Resource Identifier), such as an invalid character or an incorrectly encoded URI.