javascript / beginner
Snippet
Graceful Error Handling with Try...Catch
The try...catch block prevents your application from crashing when an error occurs. You 'try' a block of code, and if it fails, the 'catch' block handles the error.
snippet.js
1
2
3
4
5
try {const data = JSON.parse("{ invalid json }");} catch (error) {console.error("Failed to parse data:", error.message);}
nextjs
Breakdown
1
try { ... }
Contains the code that might throw an error.
2
catch (error) { ... }
This block runs only if an error occurs inside the try block.