#atom
Title: try
, catch
, and finally
in JavaScript
Content:
The try
, catch
, and finally
statements in JavaScript are used for error handling. They allow you to "try" a block of code, "catch" any errors that occur, and optionally execute a "finally" block regardless of whether an error was thrown. This mechanism helps manage runtime errors gracefully without crashing the program.
Syntax:
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that runs regardless of whether an error occurred
}
Key Concepts:
-
try
Block:- The
try
block contains the code that might throw an exception. - If an error occurs, the rest of the
try
block is skipped, and control is passed to thecatch
block.
- The
-
catch
Block:- The
catch
block is executed if an error is thrown in thetry
block. - It receives the error object, which contains information about the error (e.g.,
error.message
,error.name
). - You can use this block to log the error, display a user-friendly message, or recover from the error.
- The
-
finally
Block:- The
finally
block is optional and runs after thetry
andcatch
blocks, regardless of whether an error occurred. - It is typically used for cleanup tasks, such as closing files, releasing resources, or resetting state.
- The
Example:
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
} catch (error) {
console.error(`Error: ${error.message}`);
return null;
} finally {
console.log("Division operation attempted.");
}
}
console.log(divide(10, 2)); // 5, logs "Division operation attempted."
console.log(divide(10, 0)); // null, logs "Error: Division by zero is not allowed." and "Division operation attempted."
Error Object:
- The
error
object in thecatch
block has the following properties:name
: The name of the error (e.g.,Error
,TypeError
,ReferenceError
).message
: A description of the error.stack
: A stack trace showing where the error occurred (non-standard but widely supported).
Custom Errors:
- You can create custom error types by extending the
Error
class. - Example:
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}`); }
Linked Cards:
- Functions in JavaScript: Error handling is often used within functions.
- Control Structures in JavaScript:
try
,catch
, andfinally
are control structures for managing errors. - Objects in JavaScript: Errors are objects with properties like
name
andmessage
. - Classes in JavaScript: Custom errors can be created using classes.
- Asynchronous JavaScript: Error handling in async code (e.g., with
async/await
).
Tags: #JavaScript #ErrorHandling #TryCatch #Finally #ControlStructures #CustomErrors
Connections:
Sources: