Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/articles/javascript-tutorials/)
-   -   Exceptions In JavaScript (http://www.go4expert.com/articles/exceptions-in-javascript-t4949/)

pradeep 28Jun2007 00:44

Exceptions In JavaScript


The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

Code: JavaScript

throw "Error2"; // generates an exception with a string value
    throw 42; // generates an exception with the value 42
    throw true; // generates an exception with the value true



The exception can be a string, integer, Boolean or an object.

Note: that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!


Code: JavaScript

function userException(msg,errCode)
        this.description = msg;
        this.err = errCode;
    function divide(operand,divisor)
            var ex = new userException('Division by zero is not possible');
            throw ex;
        return operand/divisor;
        var result = divide(123,0); // trying to divide by zero
        alert('Exception: '+err.description+' ('+err.err+')');

kush_2207 28Jun2007 22:14

Re: Exceptions In JavaScript
Theres also another keyword "throws" which many times novice java geeks get confused with.
"throws" clause allows any method to throw exception to the caller. In the sense when it is used with any method, that method will not catch the exception and inturn has no exception handler. So it passes back to where it came from !

pradeep 28Jun2007 23:30

Re: Exceptions In JavaScript
Well, this is JavaScript not Java, both are very much different!

kush_2207 28Jun2007 23:35

Re: Exceptions In JavaScript
oopss...sorry posted without reading the title anyways thanks for your information.

LMatta 29Jun2007 02:45

Re: Exceptions In JavaScript
Which is the best book for beginners to read Javascript

LMatta 29Jun2007 02:46

Re: Exceptions In JavaScript
This Article is Awesome.... Able to understand it very clearly..

pradeep 29Jun2007 10:06

Re: Exceptions In JavaScript
Well I don't know about any such book, check the resources listed in the Javascript forums here!

All times are GMT +5.5. The time now is 00:10.