DEV Community

Discussion on: Handling errors in TypeScript the right way

Collapse
 
nbouvrette profile image
Nicolas Bouvrette

Do you have anything specific in mind? I actually dont use finally that much

Collapse
 
buchslava profile image
Vyacheslav Chub

Of course, me too;) But in some cases it's critical.

I mean the following use cases...

This is a good theoretical example:

try {
  throw Error('foo')
} catch (e) {
  console.log(e)
} finally {
  console.log('the end');
}
Enter fullscreen mode Exit fullscreen mode

finally works even here...

... and BTW here:

try {
  return;
} catch (e) {
  console.log(e)
} finally {
  console.log('the end');
}
Enter fullscreen mode Exit fullscreen mode

'finally' is a unique and the safest way to close/destructurise the "try-catch flow".

Let me focus on the practical part. Say, we work with the DB...

This is an anti-pattern:

let db;
try {
  db = Db.open();
  // do something
  db.close();
} catch (e) {
  console.log(e);
  db && db.close()
}
Enter fullscreen mode Exit fullscreen mode

This is a pattern:

let db;
try {
  db = Db.open();
  // do something
} catch (e) {
  console.log(e);
} finally {
  db && db.close()
}
Enter fullscreen mode Exit fullscreen mode

I hope it helps you to continue with this vital topic ;)

Thread Thread
 
nbouvrette profile image
Nicolas Bouvrette

Interesting, I didn't think of trying it while writing the article but I just tried this:

try {
  throw undefined
} catch (error) {
  console.log((error as Error).message)
} finally {
  console.log('this will log');
}
console.log('code here is unreachable because "catch" threw a TypeError')
Enter fullscreen mode Exit fullscreen mode

And yes, finally will run but your application will still be unstable. I will add an edit shortly in the article to clarify that point. Thanks for the feedback