This article explains how to use exception handling (error handling) in JavaScript.
Exception handling refers to detecting errors that occur during program execution and taking appropriate action.
What is exception handling?
Exception handling refers to detecting errors that occur during program execution and taking appropriate action. This makes the program more stable and prevents problems from occurring when unexpected errors occur.
How to write exception handling using try…catch…finally
Exception handling is done using try-catch-finally statements.
Inside the try block, we detect possible errors, and inside the catch block we handle them. Inside the finally block, write the processing that will be executed after the try and catch blocks.
Below is a sample using the try-catch-finally statement.
try {
// Processing that may cause errors
let x = y + z;
} catch(error) {
// What to do if an error occurs
console.log(error);
} finally {
// Processing always executed after try and catch blocks
console.log("finally block executed");
}
In the sample code above, a ReferenceError occurs because the values of undefined variables y, z are used in the try block. Then, it outputs an error within the catch block, and the finally block displays “finally block executed”.
catch and finally are optional. It can be specified using the following pattern.
- try…catch
- try…finally
- try…catch…finally
How to use the throw instruction to generate an exception
throw
Instructions are used by programmers to raise their own exceptions. An exception specifies an instance of the Error object or an object similar to it.
The throw instruction allows you to pass an exception that cannot be caught within a try block to a catch block. For example, you can generate your own error like this:
try {
if (x === 0) {
throw new Error("x cannot be zero");
}
let y = 100 / x;
} catch(error) {
console.log(error.message);
}
The throw instruction also allows you to define your own custom errors.
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
try {
throw new CustomError("Something bad happened");
} catch (error) {
console.log(error.name);
console.log(error.message);
}
In this way, you can create your own exception class and raise it with the throw instruction.
When using the throw instruction, be sure to handle the exception in a catch block.
About Error objects
Error objects are automatically created when an exception occurs.
The Error object contains information such as error messages and error codes, and by using this information, you can determine what kind of error has occurred.
There are different types of Error objects. For example, a SyntaxError object is generated when there is an error in JavaScript syntax. A TypeError object is generated when there is an error, such as a data type mismatch. It also allows developers to define their own Error objects.
Below is a table explaining typical Error objects.
Error object | explanation |
---|---|
Error | The base object for all error objects. |
SyntaxError | An object that is generated when there is an error in JavaScript syntax. |
TypeError | An object that is generated when there is an error such as a data type mismatch. |
RangeError | Object generated when a number out of range is used. |
ReferenceError | Object created when an undefined variable is used. |
EvalError | The object produced when the eval() function is used. |
URIError | Object created when an incorrect argument is passed to the encodeURI() or decodeURI() functions. |
InternalError | An object that is generated when an error occurs inside the JavaScript execution engine. |
Each of these Error objects represents a different type of error. For example, a SyntaxError object represents a JavaScript syntax error, and a RangeError object represents a numeric out-of-range error.
Identify the location of the error using the stack property
When an exception occurs, the Error object contains information about where the error occurred. You can use the stack property of the Error object to retrieve that information.
The stack property allows you to obtain the call stack information when an error occurs as a string. The call stack is the history of JavaScript function calls, and is information that shows which functions have called which functions, starting from the currently executing function.
The following is an example of how to obtain error information when an exception occurs.
try {
// some form of processing
} catch (e) {
console.error(e.stack);
}
This code does some processing inside the try block and executes the catch block if an error occurs. In the catch block, you can check the information where the error occurred by outputting the stack property of the Error object to the console.
The stack property contains information such as function name, file name, and number of lines, and by using this information, you can identify the cause of the error. In particular, when debugging, you can use the stack property to identify where an error occurs and trace the cause.
However, the stack property may not be supported depending on the browser or execution environment. Also, note that if no error occurs, the stack property will be an empty string.
summary
I explained how to use exception handling (error handling) in JavaScript.
- Inside the try block, detect possible errors.
- Inside the catch block, you can handle detected errors.
- Inside the finally block, write the processing to be executed after the try block and catch block.
- The throw instruction is used by programmers to raise their own exceptions.
- You can use the stack property to identify the location where the error occurs.
Exception handling is an essential element for increasing program stability. By using the try-catch-finally statement and the throw instruction, you can accurately handle exceptions that occur and increase the stability of your program.
I was able to reaffirm the importance of exception handling.
Previously, I rarely used try-catch statements, but it was nice to know how to use finally blocks.
Comments