Implement try...catch
blocks and handle errors effectively in your code.
try...catch
statement. This allows developers to anticipate potential runtime errors and respond to them gracefully without crashing the entire application. Additionally, the finally
block and custom error creation using throw
enhance the robustness and clarity of error management in code.
Here’s how you can use try...catch
for error handling in JavaScript:
function parseJSON(data) {
try {
const result = JSON.parse(data);
console.log("Parsed successfully:", result);
} catch (error) {
console.error("Failed to parse JSON:", error.message);
} finally {
console.log("Parsing attempt complete.");
}
}
parseJSON('{"name": "Alice"}'); // Valid JSON
parseJSON('{name: Alice}'); // Invalid JSON
This code demonstrates:
try
to wrap potentially unsafe code.catch
block.finally
.The try...catch
construct allows developers to handle runtime errors:
try
and catch
, regardless of the outcome.You can also use throw
to create custom errors:
throw new Error("Custom error message");
Error handling is critical for creating resilient applications that can recover from unexpected issues gracefully.
Q1: What is the purpose of the catch
block?
try
try
Answer: C. To handle runtime errors from try
Q2: What happens if an error occurs in a try
block without a catch
?
finally
will catch itAnswer: C. The script halts or throws a runtime error
Q3: What does the finally
block do?
try
and catch
regardless of outcomeAnswer: B. Executes after try
and catch
regardless of outcome
Q4: How do you throw a custom error in JavaScript?
Answer: C. throw new Error("message")