DEV Community

Discussion on: Exceptions Considered Harmful

Collapse
 
ashleyjsheridan profile image
Ashley Sheridan

Exceptions aren't harmful, unhandled exceptions may be.

Consider the example of an API endpoint that allows a user to purchase an addon for a service. How do you handle that with boolean or non-exception object returns when any of the following occur:

  • user wasn't authenticated to use the endpoint
  • user doesn't exist
  • addon doesn't exist
  • users current service subscription doesn't allow addon
  • user has no valid payment details to allow addon purchase
  • addon isn't otherwise available

The if/else logic and null object acrobatics required just to avoid exceptions would be ridiculous.

I'm not saying we pass the exceptions to the user, but not using them in your code doesn't make sense

Collapse
 
pianomanfrazier profile image
Ryan Frazier

Languages like Go, Rust, and Haskell don't have exceptions and they figured out these problems.

I knew this article would ruffle feathers when I wrote it. I wanted to present an alternative approach. I prefer explicit handling of uncertainty rather than leaving escape hatches throughout the code.

Time has shown us that no matter how careful we are Java programs will eventually throw an uncaught nullexceptionpointer. We need better mental models not more disciplined programmers.

Collapse
 
ashleyjsheridan profile image
Ashley Sheridan

I was in agreement with you about handling uncertainty properly, and exceptions allow you to do exactly that.

The fact is, we will undoubtedly need to work with 3rd party libraries et al in our code. If the language supports exceptions, then we will need to handle them. It makes sense to use them if we need to handle them at some point anyway.

Plenty of incredibly popular and powerful languages use exceptions to handle errors, that's their solution to handling the error problem. If Go & Rust don't, that's fine, it doesn't make them bad languages or mean that exceptions are bad or to be avoided.

Thread Thread
 
pianomanfrazier profile image
Ryan Frazier

My usual pattern with 3rd party libraries is to catch the exception immediately around the function call then convert it to a Result. Some functional libraries even have a helper function for this. See Purify's encase function gigobyte.github.io/purify/adts/Eit...