Console Learner — An interactive JavaScript course.


2.7 Error Handling

>>>
wrong
ReferenceError: Can't find variable: wrong
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!');
}
ReferenceError: Can't find variable: wrong
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.');
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.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.