MarcinWolny
MarcinWolny

Reputation: 1645

JavaScript Catching exception from within function or object

I encountered quite annoying problem. I can't catch errors thrown from within the functions. And to be honest - I wouldn't care much if not the fact that the same applies for throwing errors from within the JavaScript Objects.

Here's the sample code:

http://jsfiddle.net/TxsHK/1/ (you'll need firebug console to test this code)

function ViewError($CONTENT){
    this.content = $CONTENT;

    return this.content;
};


try{
    $(document).ready(function() {
    //--------------
          throw ViewError('Test error');
    //--------------
    });//$(document).ready(function() {
}catch (e) {
    if (e instanceof ViewError) {
        console.info(e.message);
    }
    else{
        console.warn(e.message);
    }
}

gives an error

TypeError: e is undefined

Why? The errors thrown by functions (or objects) should be perfectly catchable. That's the whole purpose of try - catch block: to catch exceptions out of functions. At least... so it is in other languages.

Anyone can explain what's going on? And how can I catch exceptions from within the functions / objects?

Upvotes: 0

Views: 132

Answers (1)

Pointy
Pointy

Reputation: 413996

Your "ViewError" function doesn't return anything. You're therefore throwing undefined. (edit — your fiddle is diffferent from the posted code - don't do that!)

The "ViewError" function is being called in a way that I don't think to be correct, given the way the code is written. I think you want throw new ViewError("Test error"); in order to make sure a new object is created.

There's another problem: you're expecting that you'll be able to catch exceptions thrown from that call to $(document).ready(), but that's not necessarily going to work. If the document isn't ready yet when that code runs, then you'll get no exceptions because the call returns immediately. The function you pass in would be called later, when the document is ready.

Upvotes: 2

Related Questions