Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Exception to throw when a duplicate key insertion is attempted?

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?

like image 911
Robert Oschler Avatar asked Jul 09 '11 17:07

Robert Oschler


2 Answers

Create your own exception. For example Java EE has DuplicateKeyException, you can do something similar as that for your custom map.

like image 155
Marcelo Avatar answered Sep 25 '22 09:09

Marcelo


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.

like image 21
skaffman Avatar answered Sep 24 '22 09:09

skaffman