Error Handling in JavaScript

Every programming language comes with its set of challenges and errors. These errors may arise due to several reasons, such as incorrect syntax, an unexpected behavior of certain code, or even due to improper input from a user. Just as other languages, in JavaScript too, there are ways to detect, deal with and recover from such errors. It is due to the mechanisms of error handling that a program can work in a required manner even in the case of failure of some component or an external source.

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
}
- Try Block : The part of the code that has the potential to throw an error is placed inside the `try` block. The code is run in normal manner and the `catch` block is executed only if no error occurs.

- 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
}
In this example, the run time error is generated only when a division by zero attempt is made and then the respective error message is printed by the system.

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"); 
By using the constructor of the `Error` object, you can add a message property to the error that states what went wrong. You can throw an error whenever you want based on your requirements whenever there is an unforeseen circumstance other than a runtime error or syntax error.

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.
}
In this case, we call the `checkAge` method and pass an age less than 18, which will throw a custom error instead of going to the next console statement. This custom error can then be caught and piped to the `catch` block to be handled.

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
}
No matter if the `try` block was successful in the above code or not, `finally` would run and the example uses that `finally` to hide the error that was previously caught by the `try` block. For instance, if you attempt to open a file without success, when using network applications, a resource could be created without the operation being effective.

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
}
In this case, since the error with the `try` block now has to be enforced within the `finally` block, this means the `try` block could forever or never be a success. The `finally` should enforce the last action which is to close the file and the `closeFile`'s functionality should be `finally` whether open or closed.


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
}
Related Articles