Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always wrap code in Try Catch blocks for Javascript?

Tags:

javascript

I've neglected exception handling long enough, mainly because I never see it used in the snippets I see on SO, 2 years writing javascript and I didn't even know javascript had exception handling. Other languages it is very common to see exception handling, is exception handling less important to javascript? What are some typical scenarios one should always use exception handling in javascript and shouldn't?

Does this rule apply for javascript too?

Why should I not wrap every block in "try"-"catch"?

like image 291
el_pup_le Avatar asked Apr 11 '13 11:04

el_pup_le


2 Answers

The most common strategy in javascript is to write defensively and test thoroughly.

e.g. there are libraries that start at square one with test similar to:

var element;

if (document && document.getElementById) {
  element = document.getElementById('foo');
}

if (element) {
  // use element
}    

but written in a more generic format with tests like isHostMethod.

Employ try..catch only as a last resort where feature detection or other defences aren't available. Testing host objects sometimes returns useless results or may even throw errors (e.g. all XMLHttpRequest scripts use try..catch because testing for support in IE is inconclusive so the only option is to just call it and see what happens).

Minor script errors aren't much of an issue as most browsers won't show them by default. Most non–trivial pages throw errors all the time (including SO) depending on things like the browser, settings and user's network environment. Users are just denied functionality that they may or may not be aware they are missing (and may actually benefit from). Hence a typical strategy is to make we pages functional without any script, then add script features to enhance usability. That way there is always a fallback to basic functionality if an error occurs that might otherwise prevent the page being useful.

This strategy may not always be possible, but it's a good starting point and should not be abandoned lightly.

like image 195
RobG Avatar answered Nov 10 '22 16:11

RobG


In C it was good practice to always check the return code.

Then comes the C++ with exceptions. An the Java has made really heavy usage of them, even too heavy (for example: Integer.parseInt : even if you only want to check, if something is String, you must still handle exception).

JavaScript has other concept of exception handling. A good practice is to provide a callback for exception handling. jQuery selectors still 'work' if no element is found, you get only 0-element selector.

So if you are using code that throws exceptions, you must handle it. But you should avoid throwing exceptions and support error handling via callbacks.

like image 43
Danubian Sailor Avatar answered Nov 10 '22 15:11

Danubian Sailor