Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Handle Errors in JavaScript?
Next article icon

Javascript Error and Exceptional Handling

Last Updated : 15 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, error and exception handling allows you to manage unexpected issues that occur during the execution of your code. By using tools like try, catch, throw, and finally, you can handle errors easily and prevent the program from crashing. This enables you to provide meaningful error messages, debug your code efficiently, and maintain smooth execution.

What is JavaScript Error?

In JavaScript, an error is a problem that prevents the code from running as expected. Errors can occur during development or while the application is running, causing the program to stop executing properly. There are different types of errors in JavaScript.

Types of Errors in JavaScript

  • Syntax Errors: This happens when the code doesn’t follow the correct syntax (e.g., missing parentheses, brackets, or commas).
JavaScript
console.log("Hello World"  // Missing closing parenthesis 

Output

SyntaxError: missing ) after argument list
  • Reference Errors: Occurs when we try to access a variable that hasn’t been declared.
JavaScript
console.log(x); // ReferenceError: x is not defined 

Output

ReferenceError: x is not defined
  • Type Errors: This happens when a value is not of the expected type (e.g., trying to call a method on undefined).
JavaScript
let num = 5; num.toUpperCase(); // TypeError: num.toUpperCase is not a function 

Output

TypeError: num.toUpperCase is not a function
  • Range Errors: Occurs when a value is out of range, like passing an invalid number to a function.
JavaScript
let arr = Array(-1); // RangeError: Invalid array length 

Output

RangeError: Invalid array length
  • Custom Errors: A custom error is an error that you create yourself to give more specific messages that make sense for your app. It helps you explain exactly what went wrong in a way that’s easy to understand and fix.
JavaScript
throw new Error("Custom error occurred"); 

Output

Error: Custom error occurred

Exception Handling in JavaScript

Exception handling in JavaScript refers to the process of dealing with errors (exceptions) that occur during the execution of a program. JavaScript provides some mechanisms to catch, handle, and recover from error instead of letting the error stop the program. The most common approach is using try…catch blocks.

Handling Errors Using try…catch

The try…catch statement

  • Try Block: You place code that may potentially throw an error here.
  • Catch Block: This block executes if an error occurs in the try block.
  • finally Block: The Code inside this block will always run, whether an error occurred or not.

Syntax

try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Optional: Code that runs regardless of success or error
}

Example

JavaScript
try {     let res = 10 / 0;     if (!isFinite(res)) {         throw new Error("Cannot divide by zero");     }     console.log(res); } catch (error) {     console.error("Error occurred:", error.message); } finally {     console.log("Execution completed"); } 

Output

Error occurred: Cannot divide by zero
Execution completed

In this example

  • The try block attempts to divide 10 by 0, which results in Infinity. It then checks if the result is not a finite number using isFinite(). Since division by zero gives Infinity, an error is thrown with the message “Cannot divide by zero.”
  • The catch block catches the thrown error and prints “Error occurred: Cannot divide by zero” to the console.
  • The finally block always executes, printing “Execution completed” to the console, regardless of whether an error occurred or not.

Throwing Custom Errors

Sometimes, the standard JavaScript errors are not sufficient for our application needs. In such cases, you can throw custom errors using the throw statement.

JavaScript
function check(age) {     if (age < 18) {         throw new Error("Age must be 18 or above");     }     console.log("Access granted"); } try {     check(16); } catch (error) {     console.error(error.message);     // Age must be 18 or above } 

Output

Age must be 18 or above

In this example

  • The check() function checks if the age is less than 18. If it is, it throws an error with the message “Age must be 18 or above.”
  • The try block calls the check() function with 16 as the argument. Since 16 is less than 18, an error is thrown.
  • The catch block catches the error and displays the error message “Age must be 18 or above” using console.error().

Using Finally for Cleanup

The final block is executed regardless of whether an error occurred or not.

JavaScript
try {     console.log("Trying...");     throw new Error("An error occurred"); } catch (error) {     console.error(error.message); } finally {     console.log("Cleaning up..."); } 

Output

Trying...
An error occurred
Cleaning up...

In this example

  • The try block attempts to execute the code inside it, first printing “Trying…” to the console, then throwing a new error with the message “An error occurred.”
  • The catch block catches the thrown error and prints the error message “An error occurred” to the console using console.error().
  • The finally block always runs, no matter what, and prints “Cleaning up…” to the console, ensuring any necessary cleanup happens.

Advanced: try…catch with async/await

JavaScript
async function fetchData() {     try {         let res = await fetch("https://api.example.com/data");         let d = await res.json();         console.log(d);     } catch (error) {         console.error("Error fetching data:", error.message);     } } fetchData(); 

Output:

Error fetching data: fetch failed

In this example

  • The fetchData() function uses async to allow asynchronous operations. It tries to fetch data from the URL “https://api.example.com/data” using the fetch() function.
  • If the fetch is successful, it converts the response to JSON format using await res.json() and then logs the data to the console.
  • If an error occurs during the fetch operation (like a network issue), the catch block catches the error and logs an error message with the error details.

Benefits of Exception Handling

  • Graceful Degradation: If the error occurs, then also the program keeps on running smoothly.
  • Error Logging: It helps by recording error details, making it easier to find and fix problems.
  • Prevents Crashes: It ensures the app doesn’t completely stop working when something goes wrong.

Best Practices for Error Handling

  • Catch Specific Errors: Handle specific error types if possible.
  • Use finally for Cleanup: Ensure resources are released or closed.
  • Avoid Silent Failures: Always log or handle errors appropriately.
  • Use Custom Errors: Provide meaningful error messages.


Next Article
How to Handle Errors in JavaScript?

V

VipinKashyap
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics
  • JavaScript-Errors

Similar Reads

  • Exception handling in JSP
    Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages. There are two ways of handling exceptions in JSP. They are: By errorPage and isErrorPage
    3 min read
  • Define Exception handling in ES6
    Exception: Exceptions are unwanted event that basically interrupts the normal flow of program. There are two types of exception in general:- Synchronous (eg. runtime errors)Asynchronous (eg. system errors) Exception Handling: Often a times exception happens in a program that causes the program to te
    3 min read
  • How to Handle Errors in JavaScript?
    In JavaScript Error Handling is used to find the errors in the code so, that the coder can find the particular issue to resolve it. Here are the different approaches to handle errors in JavaScript 1. Using try catch and finally statementThe try, catch, and finally blocks are used for error handling.
    4 min read
  • Which Keywords are used to handle Exceptions in JavaScript ?
    JavaScript handles exceptions through the “try..catch...finally” statement. An example statement is shown below. C/C++ Code try { // Attempt to execute this code } catch (exception) { // This code handles exceptions } finally { // This code always gets executed } The first element of a “try...catch.
    4 min read
  • The 'new' operator in Javascript for Error Handling
    In this article, we will see new operator usage during error throwing as well as handling the error() method in JavaScript using theoretical as well as coding examples. JavaScript new operator: The new operator is actually a special operator that is used along with the error() method which is the me
    3 min read
  • Exception Handling in Node.js
    Exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node.js supports several mechanisms for propagating and handling errors. There are different methods that can be used for exception handling in Node.js: Exception handli
    3 min read
  • JavaScript - throw not working in an error handling situation
    In this article, we will try to understand in which case or how does throw statement doesn't work in an error handling situation and how does or by which way possible we may correct it in order to produce the correct output with the help of certain examples in JavaScript. Let us have a look over the
    3 min read
  • How to handle exceptions in PHP ?
    Exceptions in PHP: The exception is the one that describes the error or unexpected behavior of the PHP script. The exception is thrown in many PHP tasks and classes. User-defined tasks and classes can also do differently. The exception is a good way to stop work when it comes to data that it can use
    2 min read
  • How to rethrow an exception in JavaScript, but preserve the stack?
    Stack trace conveys some portion of the data whenever an exception is thrown. The stack trace is a collection of all the methods used in the program. It starts with the method that throws an exception and ends with the method that catches the exception. In case if an exception is re-thrown, the stac
    3 min read
  • JavaScript Error() constructor
    Javascript Error() constructor is used to create a new error object. Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user. Syntax: new Error([message[, fileName[, lineNumber]]]) Parameters: message: It contains information
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences