Exception Handling
What Are Exceptions in JavaScript?
An exception in JavaScript is a disruption of the runtime of a program that - if uncaught - halts that runtime.
ECMAScript & Runtime Environments Exceptions
In JavaScript any primitive and/or object can be used to denote an exception but there are also built-in object constructors to facilitate that. Some of them are declared by the language itself (an ECMAScript exception) or by runtime environments such as browsers (a DOMException). ECMAScript exceptions include such exception constructors as Error
, ReferenceError
, SyntaxError
or TypeError
. DOM include such exception constructors as NetworkError
, TimeoutError
or NotAllowedError
. All those exception constructors have message
and name
properties defined.
foo // Uncaught ReferenceError: foo is not defined
Deliberately Throwing Exceptions
It is possible to deliberately throw an exception in code using the throw
keyword.
throw new Error() // Uncaught Error
throw 42 // Uncaught 42
throw '42' // Uncaught 42
Creating Custom Exception Objects
As already noted, any primitive, object or function can be used to denote an exception. Further, it is possible to declare a custom exception object constructor.
function MyCustomException(message) {
this.name = 'MyCustomException'
this.message = message
}
throw new MyCustomException('Something went wrong') // Uncaught MyCustomException {name: "MyCustomException", message: "Something went wrong"}
It is possible to define a property toString
to make the exception be pretty printed by various tools - MyCustomException.prototype.toString
Catching Exceptions
Both - built in exceptions and user created exceptions - can be caught and handled which can prevent a program from stopping. An exception in JavaScript is caught using the try...catch
statement.
try {
foo
} catch (e) {
console.log(e.name)
} // ReferenceError => undefined
The try...catch
statement can be extended with finally
. The code in the finally
block is executed irrespective of whether an exception was thrown, caught or even handled.
try {
foo
} catch (e) {
console.log(e.name)
} finally {
console.log('Finally!')
} // ReferenceError Finally!
Handling Specific Errors
It is possible to handle specific exceptions in the catch
block in specific ways. instanceof
keyword can be handy at that.
try {
foo
} catch (e) {
if (e instanceof EvalError) {
console.log('Not another eval error!')
} else {
console.log('Phew! Not an eval error.')
}
} // Phew! Not an eval error.
Logging Exceptions
When logging exceptions it is advised to use console.error
instead of console.log
.