What is Error Handling?
Error handling is the process of managing errors that occur during program execution so that the application doesn't crash unexpectedly.
JavaScript provides:
- try
- catch
- finally
- Throw
Why Error Handling?
Without error handling:
console.log("Start");
let result = 10 / x; // x is not defined
console.log("End");
Output:
Start
ReferenceError: x is not defined
The program stops when the error occurs.
1. try...catch
- The try block contains code that may cause an error.
- The catch block handles the error.
Syntax
try {
// risky code
} catch(error) {
// handle error
}
Example
try {
console.log(x);
} catch(error) {
console.log("Error occurred");
}
Output:
Error occurred
2. Accessing Error Information:
The error object contains details about the error.
try {
console.log(x);
} catch(error) {
console.log(error);
}
Output:
ReferenceError: x is not defined
Useful Properties
try {
console.log(x);
} catch(error) {
console.log(error.name);
console.log(error.message);
}
Output:
ReferenceError
x is not defined
3. finally
- The finally block always executes whether an error occurs or not.
try {
console.log("Try block");
} catch(error) {
console.log("Catch block");
} finally {
console.log("Finally block");
}
Output:
Try block
Finally block
Example with Error
try {
console.log(x);
} catch(error) {
console.log("Error handled");
} finally {
console.log("Always executes");
}
Output:
Error handled
Always executes
4. throw
- The throw keyword is used to create custom errors.
Example
let age = 15;
try {
if (age < 18) {
throw new Error("You must be 18 or older");
}
console.log("Eligible");
} catch(error) {
console.log(error.message);
}
Output:
You must be 18 or older
Top comments (0)