P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

How to create, design and throw built-in Error objects

UPDATE


[Rewriting question to focus on the problem I am trying to understand.]

Is there a means in JavaScript to throw Exceptions that notify the line number where the problem occurs? Similar to C#'s debugger, if an error is thrown on line 50 then I will be taken to line 50.

For example, according to MDN EvalError represents an error with eval(). So, let's say I have a function that uses eval(). I want to use a specific error that is representative of the problem at hand, EvalError:

//As written here the error implies there is a problem on this line.  See Firebug console window
var evalErra = new EvalError('required element missing from evaluation');

var stringFunc = "a=2;y=3;document.write(x*y);";

EvalString(stringFunc);

function EvalString(stringObject) {
    //Some arbitrary check, for arguments sake let's say checking for 'x' makes this eval() valid.
    if(stringObject.indexOf('x') !== -1) {
        throw evalErra;
        //throw 'required element missing from evaluation';//This way offers no line number
    }
    eval(stringFunc);//The problem really lies in the context of this function.
}

If I'm going about this all wrong, then please tell me how I should approach these kinds of issues.

Upvotes: 1

Views: 164

Answers (2)

Raynos
Raynos

Reputation: 169401

When doing error handling you want to do the following

throw new Error("message");

Then if you ever handle this error look at err.stack (firefox/opera/chrome) or err.line (Safari) or err.IE_Y_U_NO_SHOW_ME_ERROR_LINE_NUMBER (IE) to find the line number.

If you want you can subclass Error.

Upvotes: 1

Marc B
Marc B

Reputation: 360692

When you throw an error, execution of the current code will stop and JS will work its way back up the execution tree until it finds a catch () which handles the particular type of error being thrown, or gets all the way up to the top of the tree, causing an "unhandled exception" error: You threw an error, and nothing caught it, and now someone's window got broken.

try {
   if (true) {
      throw 'yup'
   }
} catch (e) { // catches all errors
   ... handle the error
}

Upvotes: 1

Related Questions