• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Best practices for Java exception handling

 
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How to coding "best practices for Java exception handling" ?

this code is good or not ::



I always conding like that.
 
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
 
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 782
Python Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 884
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 884
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks David. Your explanations helped a lot!
 
Ranch Hand
Posts: 445
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out this article on onjava.com article.Very helpful.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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).
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic