JavaScript Error Handling: try...catch

JavaScript Error Handling: try...catch

JavaScript Error Handling: try...catch

Error handling in JavaScript helps prevent scripts from crashing when unexpected issues arise. The try...catch statement allows you to handle errors gracefully.

🔹 Basic try...catch Syntax

try { // Code that might throw an error } catch (error) { // Code to handle the error }

✔️ The try block runs the code and checks for errors.
✔️ The catch block runs if an error occurs.

🔹 Example: Handling Errors Gracefully

try { let result = 10 / 0; console.log("Result:", result); // ✅ Works, since division by zero returns Infinity } catch (error) { console.log("An error occurred:", error.message); }

✔️ No error occurs, so the catch block is skipped.

Handling an Actual Error

try { let num = undefinedVariable * 2; // ❌ This will throw an error } catch (error) { console.log("An error occurred:", error.message); }

Output:

An error occurred: undefinedVariable is not defined

✔️ The script doesn’t crash, and we get an error message instead.

🔹 Using finally for Cleanup

The finally block always runs, whether an error occurs or not.

try { console.log("Trying..."); let num = 10 / 0; } catch (error) { console.log("Error:", error.message); } finally { console.log("Cleanup done."); }

Output:

Trying... Cleanup done.

✔️ Use finally to release resources (e.g., close files, stop a loader).

🔹 Throwing Custom Errors

You can manually throw errors using throw.

function divide(a, b) { if (b === 0) { throw new Error("Cannot divide by zero"); } return a / b; } try { console.log(divide(10, 0)); // ❌ Error thrown here } catch (error) { console.log("Caught Error:", error.message); }

Output:

Caught Error: Cannot divide by zero

✔️ throw let's you define custom error messages.

🔹 Handling Specific Errors with instanceof

Different errors can be handled individually.

try { JSON.parse("{ invalid json }"); // ❌ SyntaxError } catch (error) { if (error instanceof SyntaxError) { console.log("Invalid JSON:", error.message); } else { console.log("Unknown error:", error.message); } }

Output:

Invalid JSON: Unexpected token i in JSON at position 2

✔️ This is useful when handling different error types.

🔹 Summary

try → Runs the code that might fail
catch → Handles errors if they occur
finally → Runs cleanup code, no matter what
throw → Manually generate errors
instanceof → Handle specific error types

🚀 Need more examples? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close