javascript / beginner
Snippet
Basic Error Handling with try...catch
The try...catch statement allows you to handle errors gracefully. Code in the 'try' block is executed, and if it throws an exception, the 'catch' block runs.
snippet.js
1
2
3
4
5
try {const data = JSON.parse("{ invalid json }");} catch (error) {console.error("An error occurred:", error.message);}
nextjs
Breakdown
1
catch (error) { ... }
This block catches any error thrown in the try block to prevent the app from crashing.