How to Use Try Catch in JavaScript: Simple Error Handling
Use
try to wrap code that might throw an error and catch to handle that error without stopping the program. This helps your JavaScript code run safely by managing unexpected problems.Syntax
The try block contains code that might cause an error. If an error happens, the catch block runs to handle it. Optionally, finally runs code after try and catch, no matter what.
- try: Code that may throw an error.
- catch: Code to handle the error.
- finally: Code that always runs after try/catch.
javascript
try { // code that may throw an error } catch (error) { // code to handle the error } finally { // code that runs always }
Example
This example shows how try catch handles an error when dividing by zero is not allowed. The program catches the error and prints a friendly message instead of stopping.
javascript
try { let number = 10; let divisor = 0; if (divisor === 0) { throw new Error('Cannot divide by zero'); } let result = number / divisor; console.log('Result:', result); } catch (error) { console.log('Error caught:', error.message); } finally { console.log('Operation complete.'); }
Output
Error caught: Cannot divide by zero
Operation complete.
Common Pitfalls
One common mistake is forgetting to use try catch around code that can fail, which causes the program to crash. Another is catching errors but not handling them properly, which hides problems.
Also, avoid using try catch for normal control flow; it should only handle unexpected errors.
javascript
/* Wrong: No try catch, program crashes */ // let data = JSON.parse('invalid json'); /* Right: Use try catch to handle error */ try { let data = JSON.parse('invalid json'); } catch (error) { console.log('Invalid JSON:', error.message); }
Output
Invalid JSON: Unexpected token i in JSON at position 0
Quick Reference
Remember these tips when using try catch:
- Use
tryfor risky code. - Use
catchto handle errors gracefully. - Use
finallyfor cleanup code that always runs. - Don’t use
try catchfor normal logic. - Always log or handle errors inside
catch.
Key Takeaways
Wrap code that might fail inside a try block to catch errors.
Use catch to handle errors and keep your program running.
Finally runs code after try and catch no matter what.
Avoid using try catch for normal program flow.
Always handle or log errors inside catch to understand issues.