0

When instantiating an object in JavaScript, (particularly when there are multiple objects being instantiated in the same script block) - is it good practice to wrap the instantiation in a try catch statement so if the object errors it doesn't affect any other objects within the script?

E.g is it best practice for this:

try{
    new navigation();
}catch(e){
  //handle exception for navigation fail
}

try{
    new Accordian();
}catch(e){
  //handle exception for accordion fail
}

as opposed to

new navigation();
new accordian();
and so on.....
2
  • 1
    There are very few cases where errors should be thrown in JavaScript. Commented Apr 7, 2013 at 20:29
  • What are your criteria for "good"? If the criterion is "don't throw an error", then try..catch should only be used where all else fails or errors are very likely (e.g. where there is no feature test for a buggy method in some browsers). Commented Apr 7, 2013 at 23:59

2 Answers 2

1

I can't see any good reason for doing that. If the likelihood of an error being thrown from a simple object instantiation is high, there should be something very wrong with the code. Besides, try/catch statements are known to be slow in JavaScript.

Sign up to request clarification or add additional context in comments.

Comments

1

is it good practice to wrap the instantiation in a try catch statement so if the object errors it doesn't affect any other objects within the script?

No, it is not good practice to wrap the statements that new up an object in a try catch block. You instead should be looking at what kind of errors could possibly be raised when instantiating an object and move the initialization code it's own function where the errors can be handled. The contructor should not try and do too much. Keep it's reason for being simple.

Comments

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.