aspose file tools*
The moose likes Ranch Office and the fly likes Exception handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » This Site » Ranch Office
Bookmark "Exception handling" Watch "Exception handling" New topic
Author

Exception handling

Stanley Walker
Ranch Hand

Joined: Sep 23, 2009
Posts: 87
From a purely technical point of view, is it a good idea or even an acceptable coding standard to catch exceptions like indexoutofbounds, numberformatexceptions,nullpointerexceptions,etc... or the code should be so refined such that these errors never happen. eg: null check to handle nullpointerexceptions
I know many people would have very different view point, any sugegstion is welcome.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874


I believe "Runtime Exceptions" are programmers error and no code should be written to catch/handle it. Its a bug that's it and has to be cleared.
sujith Acharya
Ranch Hand

Joined: Dec 25, 2006
Posts: 60
In my opinion try/catch block is meant for handling such kind of exception.
There are 2 ways that we can prevent our application from reaching undesired state. i) avoid the occurance of Exception ii) let the Exception occur and then handle accordingly

If we take the possiblity of NullPointerException, as per case i) we check if(obj != null) {//do something} else {//do something else} as per case ii) try{//do something} catch(NullPointerException e){//do something else}
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
I think it's very rare that you should ever write a catch block that specifically catches a NullPointerException, ArrayIndexOutOfBoundsException, or other common runtime exceptions where it's easier to write a simple check before calling the method, rather than trying to pick of the pieces later. The only exception I can think of to this guideline is: it's possible there's a third-party library, outside your direct control, which usually does something useful (which you can't easily do yourself) but which occasionally throws a specific exception. In such cases you may have analyzed the behavior, and determined that the best you can do is catch the specific exception, when it happens, and then execute some workaround. Meanwhile, you file a bug report, and hope the author(s) of the code will fix the problem in a later release. This is rare, but sometimes, it happens. But for any code that you control yourself, you should never need to do this.

(Well, another exception is test code, where you intentionally create a situation which violates the contract of a method, and then verify that the appropriate exception is thrown. Nowadays most of us handle that with JUnit's @Test(expected) annotation. But sometimes you may require more precise handling than @Test offers. Anyway, test code often violates the rules of what you should do in production-level code.)

But more generally, sometimes it's entirely appropriate to write a more general catch block, such as a catch (RuntimeException e), catch (Exception e), or occasionally even catch (Throwable t). Yes, really. The thing is, while it's nice to assert that all so-called "programmer errors" (a simplistic view of runtime exceptions) shlud have been caught in testing, before release... well, sometimes it just doesn't happen. Often, really. And it's not unreasonable to install a few extra safeguards at select spots in the program. Thanks that say, look, even if we screw up the current file/order/request somehow, don't exit the program entirely. Log the error, whatever it is, and then try the next file/order/request/whatever. Some mistakes may happen, but that doesn't mean you should abandon everything. Some systems need to be a little more flexible than that. In such cases, it's entirely reasonable to catch all RuntimeExceptions, all Exceptions, or maybe even all Throwables. Yes, really.

And some people will probably tell you you shouldn't catch an Error. As general advice, especially for beginners, that's very good advice. But if anyone tells you that you should never catch an Error... ignore them. They really don't know what they're talking about. And reasoning with them probably isn't worth the hassle. Better to just wait for them to evolve or die.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Sometimes it makes sense to catch and process these exceptions. e.g. while validating user input for say age. In such scenarios catching process a NumberFormatException makes sense.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40051
    
  28
Agree. NumberFormatException is the one RuntimeException actually worth catching.
There is also the InputMismatchException, which is rather similar; Rob Prime points out that it is possible to avoid an InputMismatchException when reading from the keyboard with a Scanner, like this:
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40051
    
  28
sujith Acharya wrote:If we take the possiblity of NullPointerException, as per case i) we check if(obj != null) {//do something} else {//do something else} as per case ii) try{//do something} catch(NullPointerException e){//do something else}
Often better to make sure NPEs don't happen by actively throwing them. There are some instances where null values are to be expected (eg some leaves of trees are always null), so the if (foo != null) test is necessary. In other circumstances this is betterYou should allow your application to crash, then debug it and find where the null came from and correct that error.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40051
    
  28
I myself wrote: . . . Often better to make sure NPEs don't happen by actively throwing them. . . .
There is no truth in the rumour that I am Irish
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Test.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Oh, goodie.

After many, many, many failed attempts, it looks like the system might let me through.

Maybe only if I write in really short sentences.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
What I've been trying to post, part I:

Ah, yes, the middle ground that I forgot to mention. Yes, there are some specific runtime exceptions that it makes complete sense to catch as specific exceptions. NumberFormatException is an excellent example of this.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Ye gods - apparently it's impossible to post the rest of my message, due to "pants down" errors. Oh well.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Can I at least post individual sentences?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Great.

Part II a:

And even within the Java community,
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Part II b:

many are now rebelling against Sun's dogmata about how to handle exceptions.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Part II c:

See both Spring and Hibernate, for example - pretty much anything that goes wrong in these systems is a runtime exception, no matter whose fault it is.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Mike,
Strange. I just posted a long message successfully.
To save on effort, maybe you can type in some text editor and copy/paste?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Your test succeeded, Maneesh. And yet my own user experience remains remarkably craptastic.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Part II d:

So most anyone using these libraries of frameworks will need to occasionally catch some runtime exceptions.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Part II e:

And yet, these libraries/frameworks are quite popular and productive. Life goes on.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Done, finally.

Wow.

What an amazingly sucky user experience.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Mike Simmons wrote:Your test succeeded, Maneesh. And yet my own user experience remains remarkably craptastic.

Oh well! I will remove the test post to maintain the sanctity of the original post.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Maneesh Godbole wrote:Mike,
Strange. I just posted a long message successfully.
To save on effort, maybe you can type in some text editor and copy/paste?


That's what I've been doing.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
But every time I tried to post more than one or two sentences at a time, the system said "pants down".
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
So apparently I must talk in very short sentences.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Anyway, our local Illuminati now have more than enough data from my account (starting with timestamps and my ISP), that they can try to track down the problem, if they wish to. I need to get some sleep.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40051
    
  28
Copying thread to Ranch Office (if I can remember how to do it).

Please continue any discussion about posting problems in that version of the thread.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40051
    
  28
Please continue discussing exceptions in this thread. It is closed at present, but I shall reopen it very soon.

Please continue discussing posting difficulties here.
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10288
    
168

Mike Simmons wrote:But every time I tried to post more than one or two sentences at a time, the system said "pants down".


Is it just that specific thread where you ran into this issue? I mean were you able to post more than one or two sentences in some other thread today? Also, did you starting seeing this issue today or have your experienced it earlier too? If you have started experiences this today, can you think of the differences like the system from where you are posting any network changes?


[My Blog] [JavaRanch Journal]
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20729
    ∞

(testing)

In a nutshell:

Must do:
o Set your mower as high as it will go (3 to 4 inches).
o Water only when your grass shows signs of drought stress and then water deeply (put a cup in your sprinkler zone and make sure it gets at least an inch of water).
Optional:
o Fertilize with an organic fertilizer in the fall and spring. I recommend the Ringer brand.
o Have the pH of your soil professionally tested. Add lime if it is below 6.0 and gardener's sulfur if it is above 7.0.
o How much top soil do you have? See how deep a shovel will go into the soil. How deep can you dig a hole in one minute? Four inches of topsoil will make for an okay lawn. Eight or more inches of topsoil will make for a great lawn.

Now for the verbose details:

A little knowledge makes it so damn near anything can qualify for the "cheap and lazy" label. Including lawn care. Organic is just a bonus.

This is a game of competition. You want to make things favorable for the grass and unfavorable for the weeds so the grass will choke out the weeds. Naturally.

Mow high:



permaculture Wood Burning Stoves 2.0 - 4-DVD set
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20729
    ∞

Well, I can post bigger stuff.

This thread is a copy of another thread, right? So, is the problem still in the first thread, but not in this thread?

Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10288
    
168

paul wheaton wrote:So, is the problem still in the first thread, but not in this thread?



I tried posting a really long reply to the original thread and i was able to do it successfully.
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20729
    ∞

Mike, are you able to post longer stuff to this thread?

Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Things work fine for me now, too.

I had already posted a long reply in the same thread, shortly before the problems seen above. You can see the copy here in this thread.

Today, I've also been able to post what I wanted to originally, editing one of my posts in the original thread. A sheriff has since cleaned up the original, removing all the tiny posts and off-topic posts. You can see the fixed-up thread here. This thread retains the original content.

This used to happen more frequently, back when everyone was seeing pants-down more frequently. Back then, I noticed that at least for me, at times, my chance of posting successfully depended greatly on the length of the post. And apparently that was the case last night. This time, I didn't experiment too many different ways to do it; I just wanted to get the content out. In the past, it didn't seem to matter what forum I posted in, or what thread. A long post would be problematic no matter where I posted it, often for several hours. Meanwhile short posts would get through, usually, no matter where they were posted.

In the past, the problem seemed to correlate with where I was posting from. I have never experienced this problem posting from work, on Linux or Windows boxes. I only observe it from home, posting from my Mac laptops. I now have a different, newer laptop (still Mac though) than I did when I last had these problems. But I have the same home, same ISP. So maybe there's something special about my ISP that causes these problems; I dunno.

Or, it's also possible that my problems last night have a completely different cause than the previous problems, which I had last observed something like half a year ago. Or whenever it was - back when everyone was still seeing frequent errors, but somehow the specific behavior was different for me than for anyone else I'm aware of.

Anyway, I'll keep an eye open to see if this sort of thing recurs, and will try to gather more data if it does. Thanks for your time.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception handling