JavaScript Error Handling
What is error handling in JavaScript?
Error handling in JavaScript refers to the process of responding to and managing errors that occur during the execution of a program. It allows developers to gracefully handle unexpected situations and maintain control over the program flow.
What are the different types of errors in JavaScript?
JavaScript primarily categorizes errors into three types:
- Syntax Errors: Occur when the code does not conform to the syntax rules of the language. These errors are detected during the parsing phase.
- Runtime Errors: Occur during the execution of the program when the JavaScript engine encounters an issue (e.g., calling a function that doesn't exist).
- Logical Errors: Occur when the code runs without any syntax or runtime errors, but the output is not what was expected due to flawed logic.
How do you handle errors in JavaScript using try...catch?
The try...catch statement allows you to test a block of code for errors and handle them gracefully. The code inside the try block is executed, and if an error occurs, control is passed to the catch block.
try {
// Code that may throw an error
const result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
}
What is the purpose of the finally block in error handling?
The finally block is executed after the try and catch blocks, regardless of whether an error occurred or not. It is commonly used for cleanup actions, such as closing files or releasing resources.
try {
// Code that may throw an error
const data = getData();
} catch (error) {
console.error('Error:', error.message);
} finally {
console.log('Cleanup actions can be performed here.');
}
How can you throw custom errors in JavaScript?
You can throw custom errors using the throw statement, which allows you to create your own error messages and types.
function validateInput(input) {
if (input < 0) {
throw new Error('Input must be a non-negative number.');
}
return input;
}
try {
validateInput(-1);
} catch (error) {
console.error('Validation error:', error.message); // Validation error: Input must be a non-negative number.
}
What are the built-in error types in JavaScript?
JavaScript has several built-in error types, including:
- Error: The generic error type.
- SyntaxError: Raised for syntax errors in code.
- ReferenceError: Raised when referencing an undefined variable.
- TypeError: Raised when a value is not of the expected type.
- RangeError: Raised when a value is not within the expected range.
How can you handle asynchronous errors in JavaScript?
Asynchronous errors can be handled using try...catch blocks with async/await syntax or using the catch method of a promise.
// Using async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
}
fetchData();
// Using promises
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error.message));
What is the window.onerror method?
The window.onerror method is a global error handler that allows you to catch unhandled errors across your application. You can define a function to handle these errors and provide custom logging or user feedback.
// Global error handler
window.onerror = function(message, source, lineno, colno, error) {
console.error(`Error occurred: ${message} at ${source}:${lineno}:${colno}`);
return true; // Prevents the default browser error handling
};
How can you create a custom error class in JavaScript?
You can create a custom error class by extending the built-in Error class. This allows you to define additional properties and methods for your custom errors.
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
try {
throw new CustomError('This is a custom error!');
} catch (error) {
console.error(`${error.name}: ${error.message}`); // CustomError: This is a custom error!
}