javascript / beginner
Snippet
Error Handling with Try...Catch
Using try...catch allows your application to handle unexpected errors without crashing. If the code inside the 'try' block fails, the 'catch' block runs instead.
snippet.js
1
2
3
4
5
6
7
8
9
const fetchData = async () => {try {const response = await fetch('https://api.example.com/data');const data = await response.json();console.log(data);} catch (error) {console.error('Failed to load data:', error);}};
react
Breakdown
1
try { ... }
Contains the code that might throw an error (like a network request).
2
catch (error) { ... }
This block is executed if an error occurs, allowing you to log it or show a message.