javascript interactive

JavaScript Interactive — a console crash course


2.8 Error Handling

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
wrong
ReferenceError: wrong is not defined
Errors in JavaScript are handled with exceptions. When an exception is raised, a jump is made to the nearest error handler. In this console, errors are displayed in red.
>>>
throw 'oh no!';
"oh no!"
Exceptions can also be raised manually with the throw statement.
>>>
try {
    wrong;
} catch (e) {
    print('Ooops - ' + e);
}

  
The try...catch statement is used to handle exceptions in code. When an exception is raised inside the try block, the code jumps to the start of the catch block.
>>>
try {
    wrong;
} finally {
    print('No matter what - this happens!');
}

  
The try statement can also have a finally block, which is always executed. Whether an exception was raised or not.
>>>
throw new Error('A decent error is a good start.');

  
When throwing exceptions, care should be taken to always throw Error objects (like the example above). More on object creation and the new keyword later.
>>>

Index 1 2 3 4 5 6 7 8