JavaScript — Errors & Exceptions Handling
Errors in applications are something we can predict somewhat in advance. There are three types of errors in programming: (I) Syntax Errors, (II) Runtime Errors, and (III) Logical Errors.
Syntax Errors
Syntex Error occurs at compile at interpret time in JavaScript. It’s also known as parsing errors,
The following line causes a syntax error because it is missing a closing parenthesis.
<script type = "text/javascript"><!--window.print(;//--></script>
Runtime Errors
Runtime errors occur during execution (after compilation/interpretation). It’s also known as exceptions
The following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript"><!--window.printme();//--></script>
Logical Errors
Logic errors Are the most difficult type of errors to track down. These are not due to any syntax or runtime errors. They occur when programmers make a mistake in the logic that does not get the result as expected.
Exception handling statements
We can capture exceptions using throw statements and manage them using try…catch statements.
The try
statement lets you catch an exception if occur.
The catch
statement lets you manage the error.
The throw
statement used to explicitly throw an exception.
The try…catch Statement
The try..catch construct has two main blocks: try, and then catch:
try {
// code…
}
catch (err) {
// error handling
}
It works like this:
1. First, the code in try {…} is executed.
2. If found no errors, then catch is ignored: the execution reaches the end of try and goes on, skipping catch.
3. If an error occurs, then the try execution is stopped, and the catch block will execute with an error object.
try..catch
only works for runtime errors
try..catch
works synchronously
The try…catch…finally Statement
You can use finally block which will always execute unconditionally after the try/catch. Here is an example.
<script type = "text/javascript">
<! -
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
// →
</script>
The throw Statement
You can use throw statement used to throw a user-defined exception
throw expression;
You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:
throw 'Error2'; // String type
throw 42; // Number type
throw true; // Boolean type
throw {toString: function() { return "I'm an object!"; } };