DEV Community

Discussion on: Exceptions Considered Harmful

Collapse
 
pianomanfrazier profile image
Ryan Frazier

I suppose if static analysis can check that your function might return null it's not too evil. I would just rather have the return type be explicit and have the compiler force me to deal with the uncertainty. So I prefer pattern 4 even if you have to deal with it more. I have discovered that when refactoring out exceptions there were a lot of boundary cases I hadn't considered that I am now forced to deal with.

Collapse
 
elmuerte profile image
Michiel Hendriks

I have discovered that when refactoring out exceptions there were a lot of boundary cases I hadn't considered that I am now forced to deal with.

And that's why I prefer to use checked exceptions. It forces you to deal with it. There are cases where unchecked exceptions are alright, like constraint violations on inputs. (e.g. null even though I said it should not be null.)
But parsing functions, e.g. string to X, should always throw checked exceptions. But this is quite often not the case, so I need to lookup the documentation on what to expect when it's garbage.
Or various utility functions which are not forgiving, and throw exceptions even though a safe response is just as valid. For example "foo".substring(1,10) could have simply returned "oo" instead of throwing an out of bounds exception. Basically try to avoid creating cases where people have to deal with errors.