JavaScript Exception handling

Introduction to JavaScript Exception handling

Exceptions were not included in JavaScript until ES3. Modern JavaScript has feature to handle errors and exceptions.

We use ” try, catch, throw, and finally statements ” in JavaScript Exception handling, The try statement allows you to check for errors in a block of code. You can create custom errors with the throw statement. After try and catch, the ” finally ” statement allows you to run code regardless of the output.

JavaScript Exception handling

What are JavaScript try and catch statements?

The try statement lets you describe a block of code that will be checked for errors as it runs.
If an error occurs in the try block, the catch statement helps you to specify a block of code to be executed.
The “try and catch” statements come in pairs. The basic syntax is as follow:

try {
  Try to execute this code...
}
catch(error) {
  if error occured then handle them here...
}

Consider the following example that describes the role of try and catch statements in JavaScript Exception handling.

// Example of try and catch statements in JavaScript Exception handling.

try {
  alert("The try statement executed!");
}
catch(error) {
  alert("The catch statement executed!");
}

//

Now we will make errors in try statement. This will execute the catch statement safely. Lets see in the following example:

// Example of try and catch statements in JavaScript Exception handling.


// use undefined method inside of try statement, as a result, the catch statement will execute.


try {
  Method('this method is not defined, so it will create an error');
  alert("The try statement executed!");
}
catch(error) {
  alert("The catch statement executed!");
}



//

How to create custom errors in JavaScript?

The ” throw ” statement allows you to create a custom error in JavaScript. the basic syntax looks like this:

throw "The error message!";

Use it inside the “try and catch” statement :

try {
if(true){
throw "An error occured!";
}
}
catch(error) {
alert(The error message: ${error});
}

What is “finally statement” in JavaScript?

The “finally statement” is used in JavaScript Exception handling. When the code runs successfully or when an error occurs, the finally block is executed. for example the following example explains the usage of finally statement in error handling.

//

// Example of try, catch, and finally statements in JavaScript Exception handling.

try {
  alert("The try statement executed!");
}
catch(error) {
  alert("The catch statement executed!");
}
finally {
  alert("The finally statement executed");
}

//

Explain the error object in JavaScript?

When an error occurs, JavaScript creates an object that contains information about the error. After that, the object is passed as an argument to catch statement.
There are two properties of an error object:
1. Name
2. Message

PropertyDescription
nameSets or returns the name of an error.
messageThe error message is set or returned (as a string)

There are several errors returned by error object.

Error NameDescription
RangeErrorA number “out of range” has occurred
ReferenceErrora number that does not fall within the given limit
SyntaxErrorsyntax error in code.
TypeErrorA type error has occurred
URIErroran issue with encodeURI().

The RangeError

// Example for RangeError

let number = 3;
try {
  number.toPrecision(1000);
}
catch(error) {
  console.log(error.name);
}

// Output: RangeError

//

In the above example variable “number can’t have 1000” significant digits. so it will throw RangeError.

The ReferenceError

//Example for ReferenceError

let number = 3;
try {
  console.log(anotherNumber);
}
catch(error) {
  console.log(error.name);
}

// Output: ReferenceError

//

Since the variable “anotherNumber” is not defined yet. If you use or reference a variable that hasn’t been declared, you’ll get a ReferenceError.

The SyntaxError

If you try to test code that has a syntax error, a SyntaxError is thrown. for example, consider the following code:

//Example for SyntaxError 

try {
  console.log(eval('alert("some text)'));
}
catch(error) {
  console.log(error.name);
}

// Output: EvalError or SyntaxError 

//

The TypeError

If you use a value that isn’t in the specified type, you’ll get a TypeError.

//Example for TypeError

let str = 'text';
try {
  str.toPrecision(2);   // string can't contains significant digits
}
catch(err) {
  console.log(err.name);
}

// Output: TypeError

//

The URIError

If you use illegal characters in a URI method, you’ll get a URIError. Here is an example.

//Example for URIError

try {
  decodeURI("%%%%%%%%%");   
  // can't URI decode this URL
}

catch(err) {
  console.log(err.name);
}

// Output: URIError

//

 YouTube Video – error handling in JavaScript

Reference

https://www.w3schools.com/js/js_errors.asp

Similar Posts