Throwing & Handling Errors in JavaScript
JavaScript·4 min read·Jan 1, 2025
In computer programming, exception handling is the process of dealing with unwanted or unexpected events (essentially errors) that might disrupt the normal execution flow of a computer program.
In JavaScript, when an error is raised (or thrown), the application immediately terminates and the error is logged in the standard error of the terminal.
JavaScript error types
In JavaScript, errors can be of three types: syntax errors, runtime errors, and logical errors.
Syntax errors
Syntax errors, also called parsing errors, occur at interpret time and are related to faulty syntax, such as a missing closing brace } when defining a function, for instance.
They are uncatchable and must be corrected manually in order for the program to run as intended.
Runtime errors
Runtime errors, also called exceptions, occur during execution and are usually related to invalid user input, network connection failure, division by non numerical values, and so on.
Unlike syntax errors, runtime errors can be intercepted (or caught) and handled gracefully without necessarily crashing the application.
Logical errors
Logical errors occur when the program doesn't produce the expected result and are a direct consequence of faulty logic implementation made by the developer.
The Error class
In JavaScript, errors are created by instantiating the global built-in Error class.
new Error(message?)Where message is an optional string briefly describing the error.
Note: In JavaScript,
Errorobjects can be instantiated with or without thenewkeyword.
Unlock the Build CLI Apps in JavaScript & Node.js module
Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.
You get immediate access to:
- 45 focused lessons across JavaScript, Node.js, npm, and Git
- 17 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle