I am writing a generic API that takes parameters and returns results. I expect that if the data is consistent, only one result will be returned for an ID. If I get 1 result, I return it. If I get 0 results, I can throw "MissingResourceException" or "NoSuchElementException" etc. However, if I get multiple results, what should I throw? I have looked at the obvious places (Oracle/Java API documentation, Googling it, and of course, StackOverflow), but didn't find one.
Please note that I may not control the data, so the "the data should have been good/police your data" advice, while valid, will not help me.
Any help is appreciated.
This signals that the method can eventually throw one of those two exceptions (and also any of the unchecked exceptions). You cannnot (in Java or in any language AFAIK) throw simultaneously two exceptions, that would not make much sense.
As seen in the syntax above, all exceptions that can be thrown by a method should be declared in the method signature using the throws keyword. A method can throw multiple exceptions, which should be separated by a comma in the declaration.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.
Joshua Bloch's Effective Java says in Item 60 (Favor to use standard exceptions):
Also, feel free to subclass an existing exception if you want to add a bit more failure-capture information (Item 63).
So, I vote for one of IllegalStateException
or YourOwnException
(with additional failure-related info).
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