In JavaScript, error handling is done via the use of the `try`, `catch`, `throw`, and `finally` constructs. These enable the programmer to write the code that is able to manage errors and prevents the program from closing down in an unexpected manner.
Categories Of Errors Found in Java Script
Before we get into particulars of error handling in Java, it is better to start with identification of types of errors or mistakes that are found in JavaScript. Looking at it generally, there are three broad division of errors found in JavaScript:1. Haphazard Errors : These errors occur when the Java Script code is not written according to the correct grammar. For instance if an opening bracket is missed or a comma is out of place, syntax error will be raised by the browser and urge the code not to be successfully executed.
2. Runtime Errors : Runtime errors are those thrown up during the program execution. Missing values, invalid operations, and wrong logic are some of the factors which might result in such errors. An attempt to divide a number by zero is a common example of a runtime error.
3. Logical Errors : Logical errors are quite different from Syntax errors or Runtime errors. A logical error occurs in a situation when the program was able to run completely but at the end it produced faulty and/or results. It is somewhat easier for an executable code to exist without errors while employing logic but harder for a human to be able to detect this logical error embedded in it.
Even though it is quite unavoidable to prevent mistakes from occurring, JavaScript has many mechanisms that one can use to give graceful degradation.
The Try and Catch Statement
The `try` and `catch` statement is Javascript's favorite backbone. In this method one would be able to 'attempt' a particular code, and if that code does not run smoothly, then you use the 'catch' statement to run an alternate code in that case.The structure is as follows:
try-catch Syntax
try {
// Code that may cause an error
} catch (error) {
// Code to handle the error
}
- Catch Block : Once you've made the syntax and language as per the required standard, proceed to verify and test it, if any bug occurs during such testing, JavaScript catches it in the catch block. The catch block takes an argument which is the error object and contains information such as why it has gone bad.
For a better understanding of this concept, let's illustrate with an example.
try-catch Example
try {
let result = 10 / 0; // This will always raise an error of executing a divide by zero statement
} catch (error) {
console.log("Error: " + error.message); // This will log the error message
}
The Throw Statement
Use the `throw` statement to introduce your own errors in javascript. It would make sense in practice if there is something that hasn't gone according to plan in your code, you can throw a custom error. You can employ the `throw` statement with either an error or a string to underline the error.The syntax for throwing an error is:
Throwing a Custom Error
throw new Error("This is a custom error message");
Below is the code throwing a custom error:
Throwing a Custom Error in a Function
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or older.");
}
console.log("Age is valid");
}
try {
checkAge(16);
} catch(error) {
console.log(error.message); // Outputs: Age must be 18 or older.
}
The Finally Block
In JavaScript, `finally` blocks can be added to run after a `try` or `catch` block without caring about whether an error was thrown or not. The `finally` block is particularly beneficial in instances where certain clean up tasks need to be performed at the end such as deleting temporary files or closing a file once the `try` block has been executed.The way in which a `finally` block is used has the following syntax:
try-catch-finally Syntax
try {
// Code with a chances of failing
} catch (error) {
// Managing the error
} finally {
// Code which runs regardless of code above throwing an error or not
}
try-catch-finally Example
try {
let file = openFile("example.txt");
// Perform some operations on the file
} catch (error) {
console.log("An error occurred: " + error.message);
} finally {
closeFile(file); // Close the file no matter the try block being a success or failure
}
Error Objects
As an error occurs, an event will be generated in a JSON format which could be considered to be an object. This JSON object should contain such properties as `message` – an explanation as to what fails in the code which is caused by the `try` block.Most importantly about errors, everything that has an outline or that could contribute as a source to an error has to be a common factor such as `name` – This specifically contains the name of the source which scratches where the only part possible to throw an error is.You can use these elements to see what caused the exception. For example:
Accessing Error Object Properties
try { var x = 10 / 0;} catch (error) {
console.log("Error name: " + error.name); //Produces: Error name: Error
console.log("Error message: " + error.message); //Produces: Error message: Infinity
console.log("Stack trace: " + error.stack); //So this returns the stack trace
}