Reputation: 1282
Is there a way to tell a browser, Opera or Chrome for example, not to stop scripts execution if it encounters an unhandled exception? I just need to test some JS scripts in browser but the page also includes some code for another (non-regular browser) execution environment hence modifying code as wrapping with try/catch isn't practical.
For Chrome I've tried to put code that sets a handler function to window.onerror
which just returns true
, then error didn't appear in console but execution of scripts aborted anyway.
To be specific the page contains code for Appcelerator Titanium platform, but I'm only testing general jQuery code so I'd like to do it in a browser.
Upvotes: 2
Views: 4033
Reputation: 21522
As practical as your idea may seem, in reality it is impossible to enforce.
Comparatively, the Java programming language forces you to handle checked exceptions (exceptions you can recover from), while unchecked exceptions (such as RuntimeException
- exceptions you cannot recover from) can just happen normally at runtime outside of your control. Since they are essentially unrecoverable, your program has to stop.
Exceptions raised from the JS JVM are, unlike in java, impossible to separate in checked and unchecked categories. Because there's no such a distinction, it is not possible to avoid the script to stop.
What if you divided function/infinity? How should you recover from that?
To each distinct scenario exists a distinct answer. This is why the only remaining and valid response to your concern is to use try catch
block each time you're afraid an Exception
will happen and stop your code, and handle it specifically to that situation.
As for the window.onerror
event handler, it is irrelevant for this matter because it does not catch runtime exceptions, it catches the error that is raised when the original exception is not caught in a try catch block. That's why you get a magnificient "Uncaught exception: xxxxx" appended to the actual, original, exception message. The exception already happened, your script is already stopped, all you can do is display it the way you want at this point.
Upvotes: 1
Reputation:
If you call the suspect code in deferred fashion
setTimeout(THIS_MIGHT_THROW, 0)
then any errors thrown will terminate the "thread" or "micro-task", but not affect the rest of your execution.
Upvotes: 2