Error Handling
When something goes wrong in
JavaScript—like invalid input, missing variables, or network issues—it can
cause errors that stop your code from running. Error handling lets you
detect and manage these problems without crashing your app.
1.
The try...catch Statement
The try...catch block is used to handle errors gracefully.
try
{
let result = 10 / 0; // This won't throw an
error, but...
console.log(result); // Infinity
undefinedFunction(); // This will throw an
error
}
catch (error) {
console.log("An error occurred:",
error.message);
}
2.
finally Block
The finally block runs no matter what—whether an error occurred
or not.
try
{
let data = JSON.parse('{"name":
"John"}');
console.log("Parsed:", data);
}
catch (error) {
console.log("Error parsing JSON:",
error.message);
}
finally {
console.log("Execution completed!");
}
3.
Throwing Your Own Errors
You can create custom errors using throw.
function
divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is
not allowed!");
}
return a / b;
}
try
{
console.log(divide(10, 0));
}
catch (error) {
console.log(error.message); // Division by
zero is not allowed!
}
4.
The Error Object
The Error object provides details about the error:
try
{
nonExistentFunction();
}
catch (error) {
console.log(error.name); // ReferenceError
console.log(error.message);
// nonExistentFunction is not defined
console.log(error.stack); // Stack trace
}
5.
Common Error Types
- ReferenceError
– Variable not defined
- TypeError
– Invalid data type usage
- SyntaxError
– Invalid JavaScript syntax
- RangeError
– Number out of range