JavaScript Errors and Exceptions
In this section, we'll explore how JavaScript handles errors and exceptions. Errors can occur during program execution, but JavaScript provides mechanisms to handle them gracefully. We’ll look at different types of errors, how to handle exceptions using the try-catch block, and more advanced error-handling techniques.
Quick Links
Types of Errors in JavaScript
In JavaScript, errors are categorized into different types based on when and why they occur. These errors can be broadly divided into three main groups: syntax errors, runtime errors, and logic errors. Here's a quick overview:
- Syntax Errors: Occur when the JavaScript engine encounters code that breaks the language's grammar rules. These errors prevent the script from executing. For example, missing parentheses or unmatched braces.
- Runtime Errors: Happen when the code is syntactically correct but fails during execution. Examples include referencing undefined variables or calling functions that don’t exist.
- Logic Errors: These errors do not throw exceptions, but result in incorrect behavior or output due to flaws in the program’s logic.
1. Example of a Syntax Error
A syntax error occurs when JavaScript cannot parse the code due to incorrect formatting. These are typically caught at load or compile time.
// Missing closing parenthesis causes a syntax error
console.log("Hello, world!"
// Missing closing parenthesis causes a syntax error
console.log("Hello, world!"
Output (in browser console):
Uncaught SyntaxError: missing ) after argument list
Uncaught SyntaxError: missing ) after argument list
2. Example of a Runtime Error
A runtime error happens during the execution of the code. These are often caused by undefined variables or invalid operations like calling a non-existent function.
// Accessing an undefined variable
console.log(myVar);
// Accessing an undefined variable
console.log(myVar);
Output:
Uncaught ReferenceError: myVar is not defined
Uncaught ReferenceError: myVar is not defined
3. Example of a Logic Error
A logic error means the code runs without throwing any errors, but the output is incorrect due to a mistake in the algorithm or logic.
// Logic error: incorrect average calculation
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((a, b) => a + b, 0);
const average = sum / 4; // Incorrect divisor
console.log("The average is", average);
// Logic error: incorrect average calculation
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((a, b) => a + b, 0);
const average = sum / 4; // Incorrect divisor
console.log("The average is", average);
Output:
The average is 37.5
The average is 37.5
In this example, the logic error is caused by dividing the sum by 4
instead of the actual number of elements in the array. The correct calculation should divide by 5
.
What Are Exceptions?
Exceptions in JavaScript are runtime errors that occur when the code encounters unexpected situations. When such an error occurs, JavaScript throws an exception and, unless it is caught using `try...catch`, it will cause the script to stop execution.
Why Do Exceptions Happen?
Exceptions in JavaScript usually happen due to:
- Syntax issues: Mistakes in code structure, like missing brackets or incorrect keywords.
- Undefined variables or properties: Trying to access variables or object properties that don’t exist.
- Invalid operations: Performing operations that are not allowed, like calling something that’s not a function.
- Type errors: Operating on incompatible data types, such as trying to call a method on `undefined`.
- Network or I/O failures: Issues like failed fetch requests or accessing localStorage improperly.
Example 1: Uncaught Exception
In this example, an exception occurs because we're calling a method on an undefined variable. Since it's not handled using try-catch, the script execution stops when the error is thrown.
// Trying to call a method on undefined
const user = undefined;
console.log(user.name); // This line throws a TypeError
// Trying to call a method on undefined
const user = undefined;
console.log(user.name); // This line throws a TypeError
Output:
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
Because the exception is not caught, any code after this line will not run. This demonstrates why it's important to handle exceptions properly using try-catch.
Example 2: Calling a Non-Function
In this example, an exception occurs because we're trying to call a variable that isn't a function. This results in a TypeError, which is thrown immediately and stops the script if not handled.
// Attempting to call a non-function
const greeting = "Hello";
greeting(); // This line throws a TypeError
// Attempting to call a non-function
const greeting = "Hello";
greeting(); // This line throws a TypeError
Output:
Uncaught TypeError: greeting is not a function
Uncaught TypeError: greeting is not a function
JavaScript throws a TypeError because we're trying to invoke greeting like a function, even though it's just a string. Like other exceptions, this will interrupt the execution of the script unless it's handled.
Example 3: Accessing a Property on null
This example shows an exception that occurs when attempting to access a property on a null value. Since null is not an object, JavaScript throws a TypeError.
// Trying to access a property on null
const product = null;
console.log(product.name); // This line throws a TypeError
// Trying to access a property on null
const product = null;
console.log(product.name); // This line throws a TypeError
Output:
Uncaught TypeError: Cannot read properties of null (reading 'name')
Uncaught TypeError: Cannot read properties of null (reading 'name')
This error happens because JavaScript expects product to be an object, but it's actually null. Trying to access a property on null is not allowed and results in an exception.
Frequently Asked Questions
What is a runtime error in JavaScript?
What is a runtime error in JavaScript?
A runtime error occurs when code is syntactically correct but fails during execution, such as accessing undefined variables or calling non-existent functions.
How is a syntax error different from a logic error?
How is a syntax error different from a logic error?
A syntax error prevents code from running at all due to incorrect structure, while a logic error allows the code to run but produces incorrect results due to flawed logic.
What happens when an exception is not caught in JavaScript?
What happens when an exception is not caught in JavaScript?
If an exception is not caught using try...catch, it will typically stop the script from executing and show an error message in the console.
Can you recover from exceptions in JavaScript?
Can you recover from exceptions in JavaScript?
Yes, you can recover from exceptions using try...catch blocks. This allows you to handle errors gracefully and continue running the program.
What is the use of finally in JavaScript error handling?
What is the use of finally in JavaScript error handling?
The finally block runs after try and catch, regardless of whether an error occurred. It is useful for cleanup operations like closing files or clearing timers.
What's Next?
Now that you understand what exceptions are and how they occur, we'll move on to how to handle them effectively. In the next section, you'll learn how to use try, catch, and finally blocks to manage exceptions and ensure your code remains robust, even when unexpected errors happen.