Can I throw an exception in Javascript, that stops Javascript execution?

Use try catch finally block

It will do the trick


Answer to the title: No
Answer to "Are there different kinds of errors in JavaScript**: Yes, see MDN: Error
Syntax errors will prevent a whole script block from being executed, other errors (TypeErrors, Reference errors) will only stop the execution after the occurrence of the error.

Different <script> blocks are executed separately. You cannot prevent the second block from execution by throwing an error in the first block (Demo: http://jsfiddle.net/WJCEN/).

<script>Example: Syntax error in this script.</script>
<script>console.log('Still executed.')</script>

Also, if an error is caught using try-catch (demo: http://jsfiddle.net/WJCEN/1/), then the error will not even stop the execution a whole block.

try {throw 'Code';}catch(e){}
console.log('Still executed');


There is no general one-fit-all method to stop all code from running. For individual scripts, you can use some tricks to prevent the code from running further.

Example 1 (demo): Temporary overwrite a method

1: <script>window._alert = alert;alert=null;</script>
2: <script>alert('Some code!');confirm('Not executing');</script>
3: <script>alert=_alert;delete window._alert;alert('Done!');</script>

This method is based on the fact that script 2 expects alert to be a function. We have rewritten alert to a non-function property (script 1). Script 2 throws a TypeError, and the second block is skipped.
We restore the original values in script 3.

Example 2 (demo): Define a constant method, which cannot be overwritten.

4. <script>Object.defineProperty(window, 'test',{value:null});</script>
5. <script>var test=function(){alert('Test');};test();alert('What?');</script>

This methods relies on the Object.defineProperty method, to effectively define a constant value. In strict mode, the var test declaration would throw a TypeError: "test is read-only".
When strict mode is not enables, a TypeError will be thrown at test(): "test is not a function" (because we defined test to be constant, in script 4).

Note: The last method is not working correctly with function declarations (see bug #115452, Chrome 17)

Tags:

Javascript