When I want to create a Order in database.I need to find the good's name by goodNo.The goodNo is provider by Customer. But the goodNo is not in my database.So,I get a null value when it return.What kind of exception should i throw?IllegalAugementException?NullPointException?Or Others?
Asked
Active
Viewed 2,674 times
0
-
It depends, that's mostly your choice, based on the context. You can create your own exception to be more specific too. But that's opinion-based – AxelH Jun 26 '17 at 10:56
-
1It sounds like IllegalArgument will be more helpful than NullPointer in your case, because if someone else uses your code and gets an IllegalArgumentException he might be able to realize his goodNo is wrong, as that is one of his arguments, but a NullPointerException might lead him to believe one his arguments was null, which was not the case. Anyway, I'd go with what AxelH said and just write my own exception :D – Mark Jun 26 '17 at 10:58
-
What about Null Object Pattern? Would that be an option? – Fildor Jun 26 '17 at 10:59
-
I wouldn't use illegal argument. The allowed arguments are not defined as constant but loaded out of a database. When you get a null value out of the database it is neater to throw an npe. – Casper Jun 26 '17 at 11:04
-
Option 1: Return null - might be considered bad practice by some. Option 2: If your API returns a simple string, return an emtpy string **and document that this means "not found"** Option 3: Return a string that sais "No value found" - not my favourite, actually. If it has to be an Exception, I'd create my own Exception that you can reuse for other methods of you API, too. For example "NoItemsFoundException extends RuntimeException". Then simply throw e.g. `throw new NoItemsFoundException("The goodNo XYZ does not exist.")`. Also see https://stackoverflow.com/a/1070593/982149 – Fildor Jun 26 '17 at 11:07
-
@Casper I disagree about throwing NPE. See Mark's comment. For me as the client, I would start looking if I put null-Args into the method ... – Fildor Jun 26 '17 at 11:09
-
@Fildor I've read it and I agree that it'd be more user-friendly but when we go to the source of the problem it is an NPE. This indicates the real problem. Which is way more important to me than a neat message. – Casper Jun 26 '17 at 11:34
-
@Casper I still disagree. It is a miss in a db lookup. Which ( at least to me ) is different from some reference being null. I put it differently: Would you consider "Select * from Table where col1 > 4711" returning an empty Resultset a NPE? – Fildor Jun 26 '17 at 11:39
-
1How about [NoSuchElementException](https://docs.oracle.com/javase/8/docs/api/java/util/NoSuchElementException.html) ? _"Thrown by various accessor methods to indicate that the element being requested does not exist."_ – Fildor Jun 26 '17 at 11:42
-
@Fildor No, but as the question describes it's about a product. When I'd select a non-existing product I wouldn't use an illegal argument exception. It'd be more logical for me to throw an NPE because you're selecting something that doesn't exist. But I have to say, that after your last comment I do agree that in that case it wouldn't be logical – Casper Jun 26 '17 at 11:46
-
Thanks very much.Now I think i need design my own bisniess exception.Because I think IAE is the code level Exception.goodsNo not exist is the bisnessException.User Define Exception is better. – JainPing Jun 27 '17 at 03:10
2 Answers
1
I would discourage the use of exceptions when it is a valid use case (item not in db). Instead I would propose to consider using Optional as a return value. This indicates that the outcome of a method could be null as is the case.
Check this to see a blog with a similar example http://blog.jhades.org/java-8-how-to-use-optional/

ipper
- 624
- 4
- 13
-
Yeah,but it is sometimes make trouble.For example,methed A ->method B->methodC->...->method G.In method G,i get the null value,then i return the Optional.Then i need to check the return value in all methods from A to G.That make my code dirty. – JainPing Jun 27 '17 at 03:12
-
1And using an exception would make this different? I consider checking an optional is less dirty than a series of try catches and it is more efficient because try catch cause an overhead even when an exception is not thrown. See also https://stackoverflow.com/questions/8621762/java-if-vs-try-catch-overhead – ipper Jun 27 '17 at 06:10
-
When I throw a runtime exception in G,I only need catch the exception in a.That make methods from B to G more clean.I have considered the overhead in exception,the exception will never throw exception except that our database be revised abnormally.I just what to do some check. – JainPing Jul 04 '17 at 02:01
-
I just get this opinion in “”Thinking in Java“”.As a beginner with one year's Java experience.I need to learn from the Bruce Eckel. – JainPing Jul 04 '17 at 02:13
-
The overhead is in the try statement and not just when there is an exception. But it will be relatively small and I think other reasons are more valid not to use exceptions for control flow. This is an interesting discussion: https://stackoverflow.com/questions/8621762/java-if-vs-try-catch-overhead – ipper Jul 05 '17 at 08:04
-
/** @throws IllegalAurgementException if raw is emptyList or the content in raw is blank */ public String tryTrimStringList(String[] raw) throws new IllegalAurgementException{ ir(Collections.isEmpty(raw)){ thow new IllegalAurgementException("raw will not be emptyList"); } try{ for(int i=0;i
– JainPing Jul 15 '17 at 06:21 -
/** * @throws IllegalAurgementException if input param is blank */ public String tryTrimString(String raw)throws new IllegalAurgementException{ if(StringUtils.isBlank(raw)){ thow new IllegalAurgementException(); } return raw.trim(); } – JainPing Jul 15 '17 at 06:22
-
Firstly,I think sometimes the overhead is bearable.For excample i call the function 10000 times,will catch the Exception only one times.Besides,As stated above,i need tell the caller when i will throw the exception.Then before call me ,he need check his param.Whats'more, the exception is widely used in JDK. I think Exception is bearable. – JainPing Jul 15 '17 at 06:25
-
Maybe that,i think exception should be used in some occassion that At least one programmer need to do something(revise the code,restart the db,check the network) when the exception is throwed. – JainPing Jul 15 '17 at 06:37
-
I think the supposed overhead is not what counts. To me the problem in the initial question is a functional case that simply might occur. You search for a good by name. Only when you really expect that good to be there but suddenly it isn't (maybe due to database manipulation by another actor) I would choose for an (un)checked exception. If is is just a case of finding out if a good exists I would go for an optional as return object because this tells the caller precisely what to expect. – ipper Jul 16 '17 at 17:24
0
you can use a general exception like: DaoException
Ex:
public String Method(String atr, double atr2) throws DAOException {
try {
/*you SQL Query*/
} catch (Exception e) {
logger.error("[" + methodName + "] Error: ", e);
new DAOException( e);
} finally {
close(methodName, rs, stmt, conn);
}
}

Radu Lozovanu
- 167
- 4
- 17
-
But is just the business Exception.I think, DAOException may describe the exception my bug or some SQL exception or DBException – JainPing Jun 27 '17 at 03:04