aspose file tools*
The moose likes Java in General and the fly likes Best practices for Java exception handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Best practices for Java exception handling" Watch "Best practices for Java exception handling" New topic
Author

Best practices for Java exception handling

somkiat puisungnoen
Ranch Hand

Joined: Jul 04, 2003
Posts: 1312
How to coding "best practices for Java exception handling" ?

this code is good or not ::



I always conding like that.


SCJA,SCJP,SCWCD,SCBCD,SCEA I
Java Developer, Thailand
Dave Cronin
Ranch Hand

Joined: Apr 25, 2003
Posts: 114
This could cause problems, depending on what kind of application you are writing. One thing that may be unexpected is that it will catch every kind of RuntimeException, such as NullPointerException, ArrayIndexOutOfBoundsException. It is probably better not to catch these, since these exceptions are not recoverable. A lot of production code guideline do not allow catching Exception.

Also, the comment says it is a wrapper exception, but it has not actually wrapped the exception in the constructor argument.

Another point is that there is no logging, which may be very useful for tracing problems in log files.

Probably there is a lot more to say about correct exception handling.


Dave Cronin
SCJP, SCWCD, SCBCD
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

I'll second everything Dave says, and add one more, perhaps the biggest issue with this code: if you use "return" from a finally block, then any exception that may have been thrown from the try or catch blocks is swallowed up and disappears! The method returns normally, and no exception propagates out of the try block. The whole point of "finally" is to do some cleanup while allowing any exceptions to propagate; here we're throwing that away.


[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Although I often answer questions here, this thread has sparked a question of my own. Let's say we remove the return statement from the finally clause in order to fix the problem that EFH points out. When the try clause throws an exception, obviously execution continues with the catch clause. Now since the catch clause throws another exception, does the finally clause still execute for the original exception before the new one is propogated up the call stack?

Layne


Java API Documentation
The Java Tutorial
Horatio Westock
Ranch Hand

Joined: Feb 23, 2005
Posts: 221
If I undrestand you correctly, then yes, the finally still executes.

From the JLS (try-catch-finally):

- If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
- If the finally block completes normally, then the try statement completes abruptly for reason R.
- If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
Chengwei Lee
Ranch Hand

Joined: Apr 02, 2004
Posts: 884
Hi guys,

My question is different from the original, but it is related to the try-catch-finally dicussion.

Let's say I've a method that takes in a String representation of a date & then parses it to return a Timestamp object. In the midst of parsing, exceptions could be thrown (due to null string, invalid format, etc).

In this situation, would you guys throw an exception to indicate the problem or would you just simply return null?

By throwing an exception, I am able to know what went wrong during the parsing from a string into a Timestamp & then subsequently deciding what to do with it.

But by returning null, I do not need to have extra codes to handle these exceptions that I may throw. Also, from the null results, I would know that some errors had occur, just that I won't know what might be the problem. But then again, it may not be important to know what could be wrong.

So which would or should be the preferred way to go?

Thanks!


SCJP 1.4 * SCWCD 1.4 * SCBCD 1.3 * SCJA 1.0 * TOGAF 8
Thomas Whitmore
Ranch Hand

Joined: Aug 05, 2004
Posts: 33
Hi Cheng, people,

Let's say I've a method that takes in a String representation of a date & then parses it to return a Timestamp object. In the midst of parsing, exceptions could be thrown (due to null string, invalid format, etc).


This is a tricky question, as is most error-handling.

1) For survivability and tolerance of minor user mistakes, you want the code to continue executing with a reasonable default (null).

2) For formal testing, correctness, error diagnosis & resolution you want to report the problem.

Most Java approaches seem to follow one side or the other, but don't really fit both these requirements. eg the assert keyword is good for formal testing but bad for survivability in production.

The solution I came up with was this:
1) log a WARNING thru log4j
2) continue with a default value
3) monitor logging at warn or error levels, and assert no unexpected warning or errors at the end of each unit test.

Is this what you were thinking?


Cheers,
Thomas Whitmore
www.powermapjdo.com
[ March 08, 2005: Message edited by: Thomas Whitmore ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Cheng Wei Lee:
Let's say I've a method that takes in a String representation of a date & then parses it to return a Timestamp object. In the midst of parsing, exceptions could be thrown (due to null string, invalid format, etc).
The problem with swallowing the exceptions are as you've noted: you lose information. The only positive here is that you have an easier time calling the method if you want to ignore the errors.

I would handle it by letting the exceptions propagate and make the caller handle them explicitely. If I found I was writing a lot of code that called this method and swallowed the exceptions, I might write a parallel method that did just that.

For example, in my base DAO I have provided two methods for each type of query: findByFoo() and getByFoo(). Finders return null when not found, getters throw an ObjectNotFoundException. The idea for getters is "I know this object exists; if it doesn't there's a problem" whereas for finders it's "Give me an object like this if one exists." It's all documented very explicitely in the class and individual method JavaDocs.
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 761

David,

Incidentally Hibernate does the opposite of you.
See Session javadoc. The get method:



returns null if the object with that id does not exist. The HibernateException in the method signature above is a checked exception.
Arun Prasath
Ranch Hand

Joined: Sep 17, 2003
Posts: 192
Guys,
Dont you think returning null in any method is a poor practice??
I generally not prefere returning null from any method.
If we need to return null, on what conditions should we need to??

can anyone explain/clarify me??
thanks


SCJP 1.4, SCDJWS , SCJA<br />I can do ALL things through CHRIST who strengthens me.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Pho Tek:
Incidentally Hibernate does the opposite of you.
[get(id)] returns null if the object with that id does not exist.
Well, they just named their methods differently. load(id) is my get(id) and get(id) is my find(id). Also, they have find() methods that take other query parameters. It's just different names for the methods. I still prefer mine as they're consistent, and I started using the pattern years before Hibernate existed.

Besides, because my DAO performs all the Hibernate calls, clients of my DAO don't have to care one bit.
Chengwei Lee
Ranch Hand

Joined: Apr 02, 2004
Posts: 884
Hi David,

Originally posted by David Harkness:
I would handle it by letting the exceptions propagate and make the caller handle them explicitely. If I found I was writing a lot of code that called this method and swallowed the exceptions, I might write a parallel method that did just that.


In cases when the exception is an unchecked exception/error, will you still propagate it? Even if its a checked exception, when the information of why the exception occurs is non-important, would you still do likewise?

I've another related question. Where should we implement checks on parameters passed into a method? Should the checks be perform inside or outside of the method?

If the checks were done outside & the method is invoked only when the checks are successful, it could be highly possible that this method would never need to throw/handle exceptions.

On the other hand, if I were to do the checks inside my method, I'll need to handle it whenever the arguments were invalid. That again comes back to throwing an exception or returning null or other suitable values. But by doing so, am I violating the principles of OO? Shouldn't my method be doing what it is suppose to instead of devoting large portion of its codes in validations?

Of course I could have a separate method that does the checkings. Again, where should this method be called? Prior to invoking the method that we really want? Or inside the method that we really want?

Thanks!
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Cheng Wei Lee:
In cases when the exception is an unchecked exception/error, will you still propagate it? Even if its a checked exception, when the information of why the exception occurs is non-important, would you still do likewise?
I tend to favor unchecked exceptions where possible, limiting my use of checked exceptions to cases where I want it to be in the caller's face.
Where should we implement checks on parameters passed into a method? Should the checks be perform inside or outside of the method?
In general, encapsulate this inside the method. If you leave it outside, how long will it take for someone to call your method without checking their parameters? Or imagine how fun it will be to track down all calling code when you need to change how you check parameters.

My pattern for this is to put the following at the very top of the method:I use IAE because this is likely a coding mistake rather than a user-entered value. If it is user-entered, I validate their entry before even calling this code. The reason is that I can simply put the validation inside Struts config file and leave it at that.
Chengwei Lee
Ranch Hand

Joined: Apr 02, 2004
Posts: 884
Thanks David. Your explanations helped a lot!
Vedhas Pitkar
Ranch Hand

Joined: Jan 27, 2001
Posts: 445
Check out this article on onjava.com article.Very helpful.
Chengwei Lee
Ranch Hand

Joined: Apr 02, 2004
Posts: 884
WoW

Originally posted by Vedhas Pitkar:
Check out this article on onjava.com article.Very helpful.


It sure is helpful! Not forgeting the related articles. Thank you!
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Arun Prasath:
Dont you think returning null in any method is a poor practice??
No, sometimes it's simply the right answer. What should Map.get() return when it doesn't find the given key? What should Person.getOldestBrother() return if the Person has no siblings?

True, you can throw exceptions in these cases, but that should be reserved for exceptional cases. Not having a brother (I don't) isn't all that uncommon, so it seems a bit harsh to throw NoSuchBrotherException. Better to declare in the JavaDocs that the method returns null when the Person has no brothers and let the caller decide if that warrants an exception.

If you throw exceptions for normal cases, your code will be littered with try-catch blocks that probably swallow the exception. Look how ugly this is:I'd much rather see
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Returning null for single item not found is fine. I'm using a vendor framework with a habit of returning null for not found on methods declared to return collections. It leads to a lot of null checking when an empty collection would have communicated the results just as well. I'd rather see the empty collection. Does that sound reasonable?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
Originally posted by Arun Prasath:
Guys,
Dont you think returning null in any method is a poor practice??
I generally not prefere returning null from any method.
If we need to return null, on what conditions should we need to??

can anyone explain/clarify me??
thanks


This sounds familiar. Please don't hijack other people's threads to answer your question. There has been plenty of action on your other thread (13 replies so far).


James Carman, President<br />Carman Consulting, Inc.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Stan James:
I'm using a vendor framework with a habit of returning null for not found on methods declared to return collections. It leads to a lot of null checking when an empty collection would have communicated the results just as well. I'd rather see the empty collection. Does that sound reasonable?
I completely agree. Heck, Sun even gives you Collections.EMPTY_LIST/SET/MAP.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best practices for Java exception handling