Error Handling in Javascript
In JavaScript, things don’t always go as planned—network requests fail,
variables are undefined
,
APIs return unexpected data. Error handling helps us detect and manage these
problems so they don’t crash the entire application or cause strange behavior.
The try...catch
Statement
try...catch
lets you run code and handle
errors without stopping the program.
try {
let data =
JSON.
parse(
'{"name": "Alice"}');
console.
log(data.
name);
}
catch (error) {
console.
error(
"Something went wrong:", error.
message);
}
Adding finally
The finally
block always runs—useful for
cleanup tasks.
try {
console.
log(
"Connecting to server...");
throw
new
Error(
"Connection failed!");
}
catch (error) {
console.
error(
"Error:", error.
message);
}
finally {
console.
log(
"Closing connection...");
}
Throwing
Custom Errors
You can create your own errors with throw
.
function
checkAge(
age) {
if (age <
18) {
throw
new
Error(
"You must be 18 or older.");
}
return
"Access granted";
}
try {
console.
log(
checkAge(
15));
}
catch (error) {
console.
error(error.
message);
}
Error
Handling in Promises
For Promises,
use .catch()
:
fetch(
"https://api.example.com/data")
.
then(
response => response.
json())
.
then(
data =>
console.
log(data))
.
catch(
error =>
console.
error(
"Error fetching data:", error));
Error
Handling with async/await
With async/await
, wrap code in try...catch
.
async
function
getData() {
try {
let response =
await
fetch(
"https://api.example.com/data");
let data =
await response.
json();
console.
log(data);
}
catch (error) {
console.
error(
"Error fetching data:", error);
}
}
getData();