Welcome back to our series of tutorials on JavaScript. In this tutorial, we are going to talk about the mechanisms of error handling in JavaScript, and have a glance at how to detect, control and return errors that occurred in the application run time. Good error handling increases the reliability and user experience of your application.
What is Error Handling?
An integral part of any programming paradigm is error, or exception handling. In other words, handled in code are the predictions about the various things that may go wrong while it is being executed. In JavaScript, this is done through an in-built try.catch statement.
The try.catch statement
The try.catch statement lets you test a block of code for errors. The errors are caught in the process of executing the code. The idea is to let you decide how to handle these conditions without completely interrupting the program.
Basic Syntax
try {
// Code to try
console.log("Start execution");
throw new Error('An error occurred here');
} catch (error) {
// Handle error
console.error(error.message);
} finally {
// Code that will run regardless of an error
console.log("Cleanup actions");
}
In the below example, the code inside the try block is executed first. In case an error is thrown inside it, the control directly jumps to the corresponding catch block. And no matter the error, code inside the finally block is going to execute. This latter is typically used for clean-up work.
Handling Specific Errors
You might, for example, check the type of error caught, and decide on your subsequent actions accordingly depending on the type.
try {
let result = someFunction();
} catch (error) {
if (error instanceof TypeError) {
console.error("A TypeError occurred!");
} else if (error instanceof RangeError) {
console.error("A RangeError occurred!");
} else {
console.error("Unknown error:", error.message);
}
}
Custom Errors
You can define any kind of error in JavaScript by extending the Error class. So, this makes it more flexible and capable to throw an accurate target of error handling.
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
try {
throw new CustomError("This is a custom error");
} catch (error) {
console.error(error.name + ': ' + error.message);
}
Summary
It is a very critical thing for a professional application to be able to properly handle errors in JavaScript. Coupled with the try.catch statements and similar techniques, you might deal with any unexpected situation and prevent crashes in your programs. Try such techniques, and put them in practice in your projects. Next time, we’re going to take a look at how to deal with asynchronous programming in JavaScript and how that would help you work on more fluent, complicated application scenarios. See you then!