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 {}
Errors
in JSError
object can also be used as a base object for user-defined exceptions
.
There are several reasons why you want to avoid using Error
excessively
throwing
and try/catch
from a usual program logic.custom Error
subclasses, it may be worth reassessing why you're catering towards so many different throw
situationsthrow
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.
try
block (or in a function called from depth within the try
block) throws
an exception
, control immediately shifts to the catch
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 }