Error Handling
In JavaScript, error handling is an important aspect of writing robust and reliable code. By handling errors and exceptions properly, you can gracefully handle unexpected situations and prevent your program from crashing.
The try...catch
Statement
One way to handle errors in JavaScript is by using the try...catch
statement. This statement allows you to wrap a block of code in a try
block and catch any potential errors in a catch
block.
Here's an example:
1try {
2 // Code that might throw an error
3 const result = someFunction();
4 console.log(result);
5} catch (error) {
6 // Code to handle the error
7 console.log('An error occurred:', error);
8}
In this example, we wrap the code that might throw an error in the try
block. If an error occurs, it will be caught in the catch
block and we can handle it accordingly.
Throwing Errors
You can manually throw an error in JavaScript using the throw
keyword. This allows you to generate your own custom errors and handle them in your code.
Here's an example:
1const age = 20;
2
3if (age < 18) {
4 throw new Error('You must be 18 years old or older.');
5}
6
7console.log('Welcome to the website!');
In this example, we check if the age
variable is less than 18. If it is, we throw a custom Error
with a specified error message. The code execution will stop at this point and the error will be caught by an enclosing try...catch
statement or result in a runtime error if there's no enclosing handler.
xxxxxxxxxx
const age = 20;
if (age < 18) {
throw new Error('You must be 18 years old or older.');
}
console.log('Welcome to the website!');