Why is it discouraged to handle exceptions generically?

0
4
Asked By CuriousCoder456 On

I've been pondering the best practices around exception handling, especially the rule that advises against generically handling exceptions. Let's say you have an API endpoint called 'sendAllNotifications' which calls three functions: sendEmail, sendText, and sendLetter. My instinct tells me to wrap sendEmail in a generic exception handler because, regardless of what goes wrong, I want to ensure that sendText and sendLetter still get executed. I don't want to take a gamble that I've accounted for every possible exception that might arise from sendEmail. However, I'm confused because I keep seeing advice that says exceptions should only be caught generically at the boundary of your application. Can anyone help clarify where I might be misunderstanding this?

2 Answers

Answered By TechieTribe On

You might want to think of it as 'don't hide the reasons for failure.' If you catch every exception generically, it can obscure the actual issues that need fixing.

Answered By DevDiscussant On

Generally speaking, you actually want exceptions to cause a crash so that you can address them. If you handle exceptions generically, you risk not knowing exactly what went wrong. In your case, if sending an email fails and you wrap it generically, you could end up with one, two, all, or none of the notifications being sent, and you'd have no clue why or how many were successful. Sometimes you might not need to know the details, but often, you do.

NotificationNinja -

As a system monitor, I could log errors for each sending method that fails in my generic handler, so I would know which method had issues. That being said, I'd still want to attempt sending the other notifications even if the email fails.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.