Exception handling in javascript
Exception handling is the process of converting a code error message into a user-friendly error message. It is a necessary step in the development process.
An exception is an object with an explanation of what went amiss. Also, it discovers where the problem occurred. Errors occur due to mistakes made by developers, wrong input, or unforeseeable things.
A few reasons why exceptions occur are listed below:
- Dividing a number by zero: This results in infinity, thus throwing an exception.
- When a requested file does not exist in the system.
- When the user provides the wrong input.
- When the network drops during communication.
If a software engineer fails to plan for failure, then whatever project or code they are working on may not be successful (when an error does occur). That is where exception handling comes into play.
JavaScript error types
Different errors may occur while executing a JavaScript code. There are three types of errors.
- Syntax Errors: These are errors that cannot be interpreted by the computer. These errors stop the program from working.
- Runtime Errors: These errors take place during execution. The errors get detected when your program runs. It crashes or raises an exception. Thus, exception handlers handle exception errors.
- Logical Errors: These types of errors do not throw an error or an exception at all. This is because they result from the code not doing what the developer intends it to. It’s challenging to find logical errors. They can only be found through thorough testing.
Error objects
When a runtime error occurs, it stops the code and raises an error object.
The error object has two properties:
- Name: It gives the error name.
- Message: It sets or returns the error message in the form of a string.
JavaScript uses five types of error objects. These error objects are the foundation of exception handling.
- RangeError:
RangeError
exceptions occur when a numeric value is outside the specified range. - ReferenceError: A
ReferenceError
exception occurs when undeclared variables are used. These exceptions commonly occur due to spelling errors on variables. - Syntax Error: A Syntax Error exception occurs when JavaScript language rules get broken.
- TypeError: A
TypeError
exception occurs when a value is different from the one expected. - URIError: A
URIError
exception is raised byencodeURI()
anddecodeURI()
methods.
How to handle exceptions in JavaScript
Now that we understand what exceptions are It’s time to learn how to handle them to stop our code from crashing. JavaScript handles exceptions in try-catch-finally
statements and throw
statements.
Key Terms
- A
try-catch-finally
statement is a code or program that handles exceptions. - The
try
clause runs the code that generates exceptions. - The
catch
clause catches exceptions that are thrown. - A
finally
clause always gets executed. - The
throw
statement generates exceptions.
Try catch statements
The try
clause has the main code that may generate exceptions. If an exception is raised, the catch
clause gets executed.
Here is an example of a try-catch
statement:
function myFunction() {
const j = 70;
try {
allert("The value of j is : " + j);
} catch (error) {
alert("Error: " + error.message);
}
}
In the example above, we have made a typo error while calling the in-built alert()
function. We have misspelled alert to produce an error deliberately. The catch
clause catches the error and executes the code.
Try catch finally statements
The finally
statement is the last block to be executed. It executes after try
and catch
clauses.
Here is an example of try-catch-finally
statements:
function myFunction() {
const j = 70;
try {
alert("The value of j is : " + j);
} catch (error) {
alert("Error: " + error.message);
} finally {
alert("Finally: Finally gets executed")
}
}
Throw statements
The throw statement
is to raise your built-in exceptions.
Below is an example of a throw
statement:
function myFunction() {
const x = 50;
const y = 0;
try {
if (y === 0) {
throw ("This is division by zero error");
} else {
const z = x / y;
}
} catch (error) {
alert("Error: " + error);
}
}