JavaScript provides several ways to handle errors:
try...catch
statementsthrow
statementsError objects
finally
block
try...catch
The try...catch
statement allows you to define a block of code to test for errors.
Syntax:
try {
// code that may throw an error
} catch(err) {
// code to handle the error
}
The try
block contains code that may throw an error. If an error occurs, the catch
block is executed to handle the error.
You can have multiple catch
blocks to handle different types of errors:
try {
// some code ...
} catch(e1) {
// handle error 1
} catch(e2) {
// handle error 2
}
You can also use a finally
block which is executed regardless of whether an error occurred or not:
try {
// some code ...
} catch(e) {
// handle error
} finally {
// code to run regardless
}
throw
The throw
statement allows you to throw custom errors:
throw new Error("This is an error!");
You can throw any type of object, not just Error
objects.
Error objects
When an error occurs, an Error
object is created with:
name
- The error namemessage
- The error message
You can access these properties in the catch
block:
try {
// some code
} catch(err) {
console.log(err.name);
console.log(err.message);
}
You can also throw custom error objects with your own properties:
throw {
code: 500,
message: "Internal server error"
};
Hope this helps! Let me know if you have any other questions.