JavaScript Try...
Catch Statement - Lecture Notes
1. What is try...catch?
The try...catch statement in JavaScript is used to handle errors (also called exceptions). It allows
the program to continue running even if an error occurs.
2. Syntax
try {
// Code to try (may throw an error)
} catch (error) {
// Code to handle the error
Optionally, a finally block can be added:
try {
// risky code
} catch (err) {
// error handler
} finally {
// always runs
3. How it Works
- Code inside try is executed.
- If an error occurs, catch runs.
- If no error occurs, catch is skipped.
- finally always runs regardless of error.
4. Example: Basic Try...Catch
try {
let result = 10 / 0;
[Link]("Result is: " + result);
} catch (err) {
[Link]("An error occurred: " + [Link]);
}
5. Example: Handling a Reference Error
try {
[Link](userName); // userName is not defined
} catch (error) {
[Link]("Caught error: " + [Link]);
6. Using finally Block
try {
let x = 5;
[Link](x * y); // y is undefined
} catch (e) {
[Link]("Error: " + [Link]);
} finally {
[Link]("This will always execute");
7. Custom Error Throwing with throw
try {
let age = -5;
if (age < 0) {
throw new Error("Age cannot be negative");
} catch (e) {
[Link]("Custom Error: " + [Link]);
8. Error Object Properties
Common properties:
- name: Error type (e.g., ReferenceError)
- message: Error message
- stack: Stack trace
Example:
try {
notDeclaredVar;
} catch (e) {
[Link]([Link]); // ReferenceError
[Link]([Link]); // notDeclaredVar is not defined
9. Common Error Types in JavaScript
- ReferenceError: Accessing an undefined variable
- SyntaxError: Invalid JavaScript syntax
- TypeError: Inappropriate type usage
- RangeError: Number out of range
- EvalError: Issues with eval() function
10. Best Practices
- Use try...catch for anticipated errors (e.g., user input, API calls)
- Avoid using it for control flow
- Always log or handle the error in catch
- Use finally for cleanup tasks
Summary
Component | Purpose
------------|--------
try | Code that may cause an error
catch | Runs if error occurs
finally | Always runs (optional)
throw | Manually trigger an error