Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do uncatchable exceptions exist in Javascript?

Do any javascript runtimes (browsers, Node, etc.) ever throw uncatchable exceptions? Are any and all exceptions ever encountered in a javascript environment catchable in a try/catch statement?

like image 379
Magnus Wolffelt Avatar asked Dec 08 '14 11:12

Magnus Wolffelt


3 Answers

To generalize the other answer - exceptions that are asynchronous are generally are impossible to handle without the "bug guns" designed especially to handle them - that is domains and the process "uncaughtException" event in node and onerror in the browser.

The simplest way to get such an error would be:

setTimeout(function(){
    throw "Catch me if you can!";
});

This is what you're seeing in the http.get({host:host, port:80}, console.error); in the example of the other answer.

like image 156
Benjamin Gruenbaum Avatar answered Oct 23 '22 20:10

Benjamin Gruenbaum


If by exceptions you mean any exceptional condition that breaks your script, then all of them can throw uncatchable exceptions, since most syntax errors aren't catchable. Only syntax errors from dynamically evaluated code (eval, new Function) can be caught.

try { :( } catch(e) { } // uncatchable syntax error

That's assuming you mean catchable using try..catch. Technically you could use the error event to trap syntax errors from other script blocks:

<script> onerror = function (e) { return true; }; </script>
<script> :( </script>

On the other hand, maybe you don't consider errors that happen before evaluation to be exceptions. In that case "uncatchable exceptions" may be relegated to exceptions throws from other execution contexts (such as a function invoked with setTimeout), where you don't have control over the execution context throwing the exception. Of course, these exceptions will not disrupt the flow of your program.

like image 19
Dagg Nabbit Avatar answered Oct 23 '22 21:10

Dagg Nabbit


Some errors are really uncatchable (at least at the time of writing this post). Try to put this in Google Chrome's console:

try {
  var elm = document.createElementNS("http://www.w3.org/2000/svg", "text");
  elm.setAttribute("transform", "translate(106.7 NaN)");
} catch (e) {
  console.log('caught:', e);
}

We expect to see "caught:" and then an error data, but instead you'll see this right away:

 `Error: <text> attribute transform: Expected ')', "translate(106.7 NaN)".`
like image 1
Ruslan Zhomir Avatar answered Oct 23 '22 21:10

Ruslan Zhomir