Search within TutorialsPark

Javascript Exception Handling

Javascript Error and Exception Handling using try/catch and throw.

Javascript Function: Exception handling

In Javascript, an exception is a runtime error that the program might encounter while executing. Eg: an undefined variable, an index value referenced but not found, bad parameter etc.

Exception handlers enable the programmer to detect errors and then resolve them easily, it helps users who are unware of error messages.

Javascript Exception Handling: try/catch Statements

The Statement try is used to enclose and test parts of the program where some problem is expected. If an exception is encountered the control is shifted to catch block.

The catch block is used to enclose statements which specify what went wrong with the program. If no errors are detected, then the catch block is ignored.

Syntax: Javascript Exception handling: try/catch

Example: Javascript Exception Handling try/catch

Give it a TRY! » Note: If try/catch statements are not used, then a blank page would be displayed.

Javascript Exception Handling: throw Statement

The throw statement allows you to create your own conditions for exceptions.

Use it within the try block, to test for a specific error condition and throw it to the catch block.

Syntax: Javascript Exception Handling throw Statement

Example: Javascript Exception Handling - throw statement

Give it a TRY! » Note: The catch block is used to handle errors thrown at it by the try block .

Javascript Exception Handling: finally Clause

The finally clause is used to execute statements after the end of try block, whether or not an exception occured within the try block

Syntax: Exception Handling finally clause

Example: Javascript Exception Handling finally clause

Give it a TRY! » Note: The finally statement is executed no matter what happens to code within try block .

Javascript Error Handling : The Error Event

The JavaScript error event is fired on the window object when an error occurs.

The Event handler onerror recieves three argument : error message , URL and line Number. Whenever an error occurs , the event handler is executed after which the browser default behaviour takes over.

The default browser behaviour can be prevented by using the return value of false

Syntax: Javascript Error Handling Error Events

Example: Javascript Error Handling Error Events

Give it a TRY! » Note: Change the name of the Image file to see the error message.