10.1 The try...catch Block
Exception handling is a key aspect of programming that helps improve the resilience and reliability of your code. In JavaScript, the keywords try, catch, finally, and throw are used for exception handling. In this lecture, we'll cover these keywords, their syntax, and some usage examples.
1. The try...catch Block
The try...catch construct is used for handling errors that occur within a try block of code. If an error occurs in the try block, control is passed to the catch block, where the error can be dealt with.
Syntax:
try {
// Code that may throw an exception
} catch (error) {
// Code to handle the exception
}
In this example, although division by zero doesn't cause an error in JavaScript, if it were a different error (like accessing an undefined variable), the catch block would handle it:
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.error('An error occurred:', error);
}
10.2 The finally Block
The finally block is used for executing code that must run regardless of whether an exception occurred in the try block or not. The finally block follows the catch block.
Syntax:
try {
// Code that may throw an exception
} catch (error) {
// Code to handle the exception
} finally {
// Code that will always execute
}
In this example, the message This will always execute. will be printed regardless of whether an error occurred or not:
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.error('An error occurred:', error);
} finally {
console.log('This will always execute.');
}
10.3 The throw Statement
The throw statement is used to explicitly throw exceptions. You can use it to throw custom errors.
Syntax:
throw expression;
Where:
expression: any expression or object to be thrown as an exception
Example Use
In this example, an error is thrown if you try to divide by zero, and the catch block handles this error:
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed.');
}
return a / b;
}
try {
let result = divide(10, 0);
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
}
10.4 Advanced Examples and Use Cases
Example 1: Multiple Exceptions
Sometimes different types of errors can occur within a try block. You can handle them differently using the properties of the error object.
In this example, we handle a JSON syntax error separately from other possible errors:
try {
JSON.parse('{ malformed JSON string }');
} catch (error) {
if (error instanceof SyntaxError) {
console.error('JSON Syntax Error:', error.message);
} else {
console.error('Unexpected Error:', error);
}
} finally {
console.log('Parsing attempt finished.');
}
Example 2: Nested try...catch Blocks
You can use nested try...catch blocks for more fine-grained error handling.
In this example, an error occurring in the first try block is handled by the inner catch block, which then rethrows the error for handling by the outer catch block:
try {
try {
let result = divide(10, 0);
console.log(result);
} catch (innerError) {
console.error('Inner catch:', innerError.message);
throw innerError;
}
} catch (outerError) {
console.error('Outer catch:', outerError.message);
} finally {
console.log('Nested try...catch finished.');
}
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed.');
}
return a / b;
}
Example 3: Using finally to Release Resources
The finally block is useful for releasing resources, like closing files or ending network connections.
In this example, the file will always be closed, regardless of whether an error occurred during reading:
function readFile(filePath) {
let file;
try {
file = openFile(filePath); // Function to open the file
// Work with the file
} catch (error) {
console.error('Error reading file:', error.message);
} finally {
if (file) {
closeFile(file); // Function to close the file
}
console.log('File processing finished.');
}
}
function openFile(path) {
// Logic to open the file
}
function closeFile(file) {
// Logic to close the file
}
readFile('path/to/file.txt');
Exception handling in JavaScript using try, catch, finally, and throw enables you to create more robust and resilient applications. Understanding and effectively using these constructs helps manage errors efficiently, release resources, and enhance user experience.
GO TO FULL VERSION