Repeatedly I see comments about avoiding throwing generic RuntimeException
and I am trying to follow that guideline.
I have a class that aggregates a SortedMap
with a property setting to allow or disallow duplicate keys. I am trying to figure out what Exception I should throw when duplicate keys are disallowed and an attempt is made to add one.
I checked the Java docs for the Exception
class and none of the known direct descendants seemed suitable. Do I just go ahead and create my own EDuplicateMapKey
class for example and throw that? If so, how do I avoid ending up with a big pile of class files, one for each custom Exception
type?
What is considered "best practice" here?
Create your own exception. For example Java EE has DuplicateKeyException
, you can do something similar as that for your custom map.
Do I just go ahead and create my own EDuplicateMapKey class for example and throw that?
Absolutely, yes. DOn't be afraid to create new exception types if it feels like the right way to go. If it's not clear to you, as the author, which is the right exception type to use, then it certainly won't be clear to the programmer using your API. So make it explicit, and create your own exception type.
How do I avoid ending up with a big pile of class files, one for each custom Exception type?
Exception classes are no different to any other business logic type. You don't feel restrained in creating as many types as you feel is necessary for your "normal" code (at least, I hope you don't), and you should feel no differently when it comes to exception types. They're often just as important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With