0

I am new to the web development world and I would like I am lost in the steps of creating an exception in a java script function

what I want to ideally do is something following the following syntax ...

function exceptionhandler (){
     if (x===5)
     {
          //throw an exception
     }
}

I found the following tutorial http://www.sitepoint.com/exceptional-exception-handling-in-javascript/ But I don t know how to convert the above if statement into a try..catch...finally exception

thanks!

6
  • That doesn't look like the place for a try..catch, but for throwing an exception. Could you elaborate a little?
    – bfavaretto
    Commented Feb 14, 2013 at 18:12
  • what I need it to have a conditional exception , and based on my readings this I understood that the try catch scenario is the one that catches the errors ... you can correct me if I am wrong by all means :) Commented Feb 14, 2013 at 18:22
  • Yes, but try..catch will catch an exception if it already occurred. A check for equality like if(x===5) will never throw an exception.
    – bfavaretto
    Commented Feb 14, 2013 at 18:25
  • @bfavaretto orly === false - ReferenceError: orly is not defined
    – Paul S.
    Commented Feb 14, 2013 at 18:35
  • @PaulS. Correct! I retract my previous comments...
    – bfavaretto
    Commented Feb 14, 2013 at 18:36

2 Answers 2

3

To create an error in JavaScript you have to throw something, which can be an Error, a specific type of Error, or any Object or String.

function five_is_bad(x) {
    if (x===5) {
        // `x` should never be 5! Throw an error!
        throw new RangeError('Input was 5!');
    }
    return x;
}

console.log('a');
try {
    console.log('b');
    five_is_bad(5); // error thrown in this function so this 
                    // line causes entry into catch
    console.log('c'); // this line doesn't execute if exception in `five_is_bad`
} catch (ex) {
    // this only happens if there was an exception in the `try`
    console.log('in catch with', ex, '[' + ex.message + ']');
} finally {
    // this happens either way
    console.log('d');
}
console.log('e');
/*
a
b
in catch with RangeError {} [Input was 5!]
d
e
*/
1
  • Again, I think you understood the OP better than I did. +1
    – bfavaretto
    Commented Feb 14, 2013 at 18:42
0

You may be looking for something like this:

function exceptionhandler() {
    try {
        if (x===5) {
            // do something  
        }
    } catch(ex) {
        throw new Error("Boo! " + ex.message)
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.