Error and Exceptions
What is it
Error
object is thrown
when runtime error
occurs.
Unlike other languages, Error and Exceptions are the same thing in JavaScript
The Error
built-in constructor is a standardized facility for creating objects to throw with commonly-useful features.
new Error(); Object.create(); class extends Error {}
Creating custom Errors
in JS
Error
object can also be used as a base object for user-defined exceptions
.
constructor(message) { super(message); // Not required, but makes uncaught error messages nicer. this.name = 'FileNotFoundException'; } } // Example usage function readFile(path) { throw new FileNotFoundException(`The file ${path} was not found`); } try { readFile('./example.txt'); } catch (err) { if (err instanceof FileNotFoundException) { // Handle the custom exception console.log(`Could not find the file. Reason: ${err.message}`); } else { // Rethrow it - we don't know how to handle it // The stacktrace won't be changed, because // that information is attached to the error // object when it's first constructed. throw err; } }
Caveat
There are several reasons why you want to avoid using Error
excessively
- Throwing an exception is expensive
- This discourages
throwing
andtry/catch
from a usual program logic. - If you're building a ton of
custom Error
subclasses, it may be worth reassessing why you're catering towards so many differentthrow
situations
throw
Any value
can be thrown
in JS:
throw "Error2"; // String type throw 42; // Number type throw true; // Boolean type throw { toString() { return "I'm an object!"; }, };
try...catch
try/catch
handles exceptions
thrown by arbitrary levels of function calls within the try
block, like most other languages with that feature.
- If any statement within the
try
block (or in a function called from depth within thetry
block)throws
anexception
, control immediately shifts to thecatch
block.
try { // throws an exception throw "myException"; } catch (err) { // statements to handle any exceptions logMyErrors(err); // pass exception object to error handler }
The catch
(value) clause is not typed in JS, as it is in other language like Java.
Thus, unlike Java, multiple catch
blocks for a single try
doesn't make sense in JS.
However, we can use following syntax to add contextual information to the Error that was thrown:
if (badCondition) throw new Error("Bad Condition");
finally
finally
block contains statements to be executed after the try...catch
blocks execute
It is also important to note that the finally
block will execute whether or not an exception is thrown.
openFile(); try { writeToFile(someData); // This may throw an error } catch (e) { handleError(e); // If an error occurred } finally { closeFile(); // Always closes the resource }