Javascript Error Handling

JavaScript has two basic levels of error handling: syntax errors and runtime errors.

Javascript Syntax Errors

In Javascript, syntax errors occur when code interpret before it start execution.

Javascript Syntax Errors Example

Javascript Runtime Errors

Runtime errors also known as exception occur due to an illegal operation during execution of Javascript code.

Javascript Javascript Runtime Errors Example

Try...Catch...Finally & Throw

In Javascript, the most comman way to handle runtime errors is try..catch...finally statement. The try...catch...finally statement provides a way to handle all of the errors that may occur in a given block of code, while still running code. If errors not handled by the code, JavaScript provides the default error message. Try...Catch...Finally statement can be used to capture two types of errors: runtime errors and user errors.

Syntax

Try - block contains code that throw error or excetion.
Catch - block contains code that handle errors.
Finally - block is always run unless an unhandled error occurs.

Javascript Try...Catch Example

In the above example the "undefindeMethod()" method not defined and script os trying to invoke the method in catch block. Code in catch block is throwing error or exception, thus document.write statement will not execte here. Catch block will execute here to handle the error or exception thrown by catch block.

Above example will produce following result

Javascript Try...Catch...Finally Example

In the above example if you can see the "undefindeMethod()" method has been commented in the catch block. Code in catch block is not throwing any error or exception, thus document.write statement will execte. Because no exception occure in try block, the catch block won't execute.

Above example will produce following result