JavaScript Error Handling
Errors happen: a wrong input, a missing file, a lost network. If an error is not handled, the script stops. Error handling lets the program continue with a good message.
try, catch and finally
try {
console.log("Start");
let result = undefinedVariable + 1; // error
console.log("This line is skipped");
} catch (error) {
console.log("Error name: " + error.name);
console.log("Message: " + error.message);
} finally {
console.log("This always runs");
}
Output of the above program is
Start
Error name: ReferenceError
Message: undefinedVariable is not defined
This always runs
try: the code that may fail.catch: runs only if an error happens. The error object hasnameandmessage.finally: always runs, good for cleanup.
throw your own error
function setAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative");
}
return age;
}
try {
setAge(-5);
} catch (e) {
console.log(e.message);
}
Output of the above program is
Age cannot be negative
Common error types
| Error | When |
|---|---|
ReferenceError | Using a variable that does not exist |
TypeError | Using a value in a wrong way, like calling something that is not a function |
SyntaxError | Code or JSON with wrong syntax |
RangeError | A number outside the allowed range |
try {
null.name;
} catch (e) {
console.log(e.name);
}
Output of the above program is
TypeError
Note:
Do not hide errors with an empty catch block. At least log them with console.error(error). Errors in asynchronous code are handled in async/await with the same try...catch.
Summary
- Put risky code in
tryand handle problems incatch. - Use
throw new Error("message")to raise your own errors. - Next: JavaScript Events.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |