exceptional handling in javascript

What is exceptional handling? Why we use exceptional handling? How to handle exceptions? Syntax Errors Runtime Errors How to return error name in tr

exceptional handling in javascript

Photo by Tai Bui on Unsplash

What is exceptional handling?

Exceptions are that bugs which may occur during the code execution. Exception handling is a technique in programming to handle errors and exceptions that occur during the execution of a program.

Why we use exceptional handling?

There are many uses of using exception handling in our programs. Some of them..

  1. It deal with the errors properly and avoids the code from crashing and keeps the code running smoothly.

  2. If any error is encountered we can get some error messeage which give us some information on what's happening inside our code.

  3. It makes easier to debug our code. we can know the exact location where the error occurred.

How to handle exceptions?

To handle exceptions, we have to know the types of errors in javascript.

There are two main types of errors in Javascript.

  1. Syntax Errors: It occurs when the code syntax is not proper and the Javascript interpreter can't understand it. This error can't be handled with exception handling.

  2. Runtime Errors: It occurs while the code is executing, such as when trying to access an undefined variable or when a function is not found. These errors can be handled using exception handling.

In javascript, only runtime errors can be handle by exception handling.

To handle runtime errors, we use try-catch statements or try-catch-finally statements.

What is try-catch statements?

Syntax:

try

{

//block of code for testing.

} catch{

//block of code for addressing errors

} finally{

// finally code executes before control flow exists

}

try{}

It is a piece of code that needs to be tested during the execution of code. The try statement's block of code is checked first, if any errors are encountered, then the try{} statement passes it to the catch{} statement.

catch{}

If any errors are encountered by try{} statement, the catch {} statement gets executed otherwise the catch{} statement gets skipped.

finally{}

It is required either try-catch or try-finally be presented.

Examples

Here is some code in which variable is not defined.

Here is the code to handle exception. And it executes the whole code until last statement.

How to return error name in try-catch?

Here is the code to return only name of the error.

How to return error messege in try-catch?

Here is the code to return only error messege.

Did you find this article valuable?

Support WebIndia by becoming a sponsor. Any amount is appreciated!