JavaScript Errors
A robust application must expect the unexpected. Using error handling structures like try...catch prevents your scripts from failing silently or catastrophically crashing the user's browser.
The Try...Catch Block
The try statement defines a block of code to be tested for errors while it is being executed. The catch statement defines a block of code to be executed, if an error occurs in the try block.
If an error happens, the normal execution flow stops immediately. The JavaScript engine "unwinds" the Call Stack until it finds a catch block to handle the exception. If none is found, the program halts.
The Error Object
When an error is caught, it is passed to the catch block as an object. This object typically has two main properties:
- name: Sets or returns an error name (e.g., ReferenceError).
- message: Sets or returns an error message detailing what went wrong.
The Finally Block
The finally statement lets you execute code, after try and catch, regardless of the result. It is incredibly useful for cleaning up operations—such as closing database connections or hiding loading spinners—that must happen whether the operation succeeded or failed.
Throwing Custom Errors
The throw statement allows you to create a custom error. Technically you can throw a string, number, boolean or an object, but it is best practice to throw a new instance of the Error class to ensure you preserve the stack trace.
View Full Transcript+
This section contains the full detailed transcript of the video lessons for accessibility purposes and quick review. It covers Syntax Errors vs Runtime Errors, extending the Error object with custom classes, and patterns for checking error types using the instanceof operator inside catch blocks.
