JavaScript - Errors & Exceptions Handling
Hello there, future JavaScript wizards! ? Welcome to our exciting journey into the world of error handling in JavaScript. As your friendly neighborhood computer teacher, I'm here to guide you through this adventure. So, buckle up, and let's dive in!
What is an Error?
Imagine you're baking a cake ?, and you accidentally use salt instead of sugar. That's an error! In programming, errors are similar - they're unexpected issues that occur when our code runs. These can be typos, logical mistakes, or even problems with the data we're working with.
Here's a simple example of an error in JavaScript:
console.log(Hello, World!);
If you run this code, you'll get an error because we forgot to put quotes around our text. JavaScript expects strings to be in quotes.
What is Error Handling?
Error handling is like having a safety net when you're walking on a tightrope. It's a way to gracefully manage errors in our code, preventing our entire program from crashing when something goes wrong.
The try...catch...finally Statement
The try...catch...finally
statement is our primary tool for handling errors in JavaScript. It's like a superhero trio coming to save the day! ?♀️?♂️?♀️
Here's how it works:
try {
// Code that might cause an error
let result = 10 / 0;
console.log(result);
} catch (error) {
// Code to handle the error
console.log("Oops! An error occurred:", error.message);
} finally {
// Code that always runs, regardless of errors
console.log("This always runs!");
}
In this example:
- The
try
block contains code that might cause an error (dividing by zero). - If an error occurs, the
catch
block catches it and handles it gracefully. - The
finally
block always runs, whether there was an error or not.
The throw Statement
Sometimes, we want to create our own custom errors. That's where the throw
statement comes in handy. It's like being the referee in a game and calling a foul! ?
Here's an example:
function checkAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative!");
}
console.log("Age is valid:", age);
}
try {
checkAge(-5);
} catch (error) {
console.log("Caught an error:", error.message);
}
In this code, we're throwing a custom error when someone tries to use a negative age. The catch
block then handles this error.
The onerror Event Handler Property
The onerror
event handler is like having a watchful guardian for your entire JavaScript application. It catches errors that occur anywhere in your code.
Here's how you can use it:
window.onerror = function(message, source, lineno, colno, error) {
console.log("An error occurred:");
console.log("Message:", message);
console.log("Source:", source);
console.log("Line:", lineno);
console.log("Column:", colno);
console.log("Error object:", error);
return true;
};
// This will trigger the onerror handler
nonExistentFunction();
This code sets up a global error handler that will catch any uncaught errors in your application.
JavaScript Error Object Reference
JavaScript provides several built-in error types. Let's look at them in a handy table:
Error Type | Description |
---|---|
Error | The generic error type |
SyntaxError | Occurs when there's a syntax error in the code |
ReferenceError | Occurs when referencing a non-existent variable |
TypeError | Occurs when a value is not of the expected type |
RangeError | Occurs when a number is outside the allowable range |
URIError | Occurs when using incorrect URI functions |
EvalError | Occurs in relation to the eval() function |
Here's an example of how these errors might occur:
try {
// SyntaxError
eval("Hello World");
// ReferenceError
console.log(undefinedVariable);
// TypeError
null.f();
// RangeError
let arr = new Array(-1);
// URIError
decodeURIComponent("%");
} catch (error) {
console.log(error.name + ": " + error.message);
}
Each of these lines will throw a different type of error, which our catch
block will handle.
And there you have it, my dear students! We've journeyed through the land of JavaScript error handling. Remember, errors are not your enemies - they're valuable feedback that helps you improve your code. Embrace them, learn from them, and soon you'll be handling errors like a pro! ?
Keep coding, keep learning, and don't forget to have fun along the way! See you in our next lesson! ?
Credits: Image by storyset