Becareful With Try Catch Finally Javascript Concept

Wikla pandu
2 min readDec 17, 2023

--

Photo by Caleb Woods on Unsplash

Do you often use try and catch in javascript?
Maybe those of you who have consumed APIs with javascript are familiar with them.

In javascript we usually use it like this

const getData = async () => {
try {
throw new Error('reject')
} catch (error) {
console.log('error: ',error)
}
}

getData();

But sometimes besides using try and catch we also use finally.

const getData = () => {
try {
throw new Error('reject')
} catch (error) {
console.log('error: ',error)
} finally {
console.log('done');
}
}

getData();

Guess what happens if we do return instead of console.log.

const getData = () => {
try {
throw new Error('reject');
} catch (error) {
return error;
} finally {
return 'done';
}
}

console.log(getData());

For those of you who think the result of console.log is “reject” then you are wrong.
if we use try catch finally but in finally you do return then the result you get is the return of finally.

Then I can conclude, I don’t recommend you to use finally as a return.

Thank you for reading my short article. hopefully it can help you a little and add some new knowledge.

--

--

Wikla pandu
Wikla pandu

No responses yet