Errors
Many times there arises an error during program execution due to invalid input, programming mistakes/errors etc.
Suppose you are converting a user entered value to an integer. While you expect the user to enter number but he enters a string, your code blows away.
Programming errors involve calling a function when it is not defined, performing an operation on a variable whose value is null or undefined etc.
Errors arising in above scenarios are called runtime errors or exceptions since they arise at run time.
Handling errors
Runtime errors need to be handled. Handling errors means performing a graceful action when error occurs such as displaying a meaningful message and not depending on the message shown by the javascript engine. Example, below code calls a function which has not been defined.

func();

This code when executed raises this error.

Uncaught ReferenceError: func is not defined
at <anonymous>:1:1

Above message although explanatory does not look good. In professional applications, these kind of errors should be gracefully handled.
Further, in case such an error arises, the code written after the line which raised the error is not executed which is not desired many times.
try-catch
Javascript provides try-catch statements to handle erroneous or risky code. Code that may raise an error is placed inside try block followed by the catch block. If an error is raised inside the try block, control goes to catch block where the error is handled either by showing an alert or as a text on the web page. Do not use console.log to show errors since the console is only used by developers and not end users.
Syntax
Below is the syntax of trycatch in javascript.

try {
   // risky code
} catch(e) {
  // handle error
}

When the error arises inside try block, the control moves to catch block. Example,

try {
   console.log('Executing risky code');
   // call an undefined function 
   func();
   console.log('Risky code executed');
} catch(e) {
  console.log('Undefined function');
}
console.log('Risky code executed');

Above code produces below output

Executing risky code
Undefined function
Risky code executed

Statements after the line where the error is raised in try are not executed. catch block receives the error object as argument. Name of error object can be any user defined name, it need not be e.
Note that the statements after trycatch are executed normally even after the error is raised.
throwing Error
Sometimes you do not want to execute further code if a certain condition is not met. In such cases, an error can be deliberately thrown by using throw keyword. throw is used to prevent the code ahead from being executed.
Suppose you want to get the second element of an array and show it on the web page. Before retrieving the element, you should check the total number of elements of the array. If it has only one element, there is no point in getting the second element. Thus, you check the length and if it is less than 2, then throw an error with a meaningful message.
An error is thrown by creating an object of Error class using new operator. This object takes a string as argument which represents the reason of error being thrown. Example,

let arr = [2];
try {
   console.log('Checking array length');
   // check if array has second element
   if(arr.length < 2) {
      // throw error
      throw new Error('Array does not contain enough elements');
   }
   console.log('Printing second element');
   // write second element
   document.write('Second element is ' + arr[1]);
} catch(e) {
   console.log(e);
}

In the above example, if the array length is less than 2, then error is thrown. Output of above execution is

Checking array length
Error: Array does not contain enough elements
at <anonymous>:7:10

Notice how the above error message is the same that was thrown. Also, the above error was handled by our own program. If there was no try-catch block and this error is handled by the javascript engine, then you will see an Uncaught Error before the error message.

Leave a Reply