aspose file tools*
The moose likes Beginning Java and the fly likes Exception handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
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: 10523
    
    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: 39834
    
  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: 39834
    
  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: 39834
    
  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
Maneesh wrote: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.

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.

And even within the Java community, many are now rebelling against Sun's dogmata about how to handle exceptions. 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. So most anyone using these libraries of frameworks will need to occasionally catch some runtime exceptions. And yet, these libraries/frameworks are quite popular and productive. Life goes on.
Stanley Walker
Ranch Hand

Joined: Sep 23, 2009
Posts: 87
thank you all for your inputs. really appreaciate it.
so to just sum it up, exceptions like the ones mentioned , it is not advisable to catch such exceptions. instead code should be so refined such that these exceptions do not ever occur. Thankx Mike , your explanation really helped.
however i have just one doubt. i know many senior associates in my project who advocate using try{} catch(Exception e){} usage. their explanation is code should never reach melting point no matter what the situation is. is this advisable?
and also what would you guys suggest, should i throws Exception @ method definition or individually catch the exceptions. i prefer catching exceptions but is it a good programming practice?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Stanley Walker wrote:however i have just one doubt. i know many senior associates in my project who advocate using try{} catch(Exception e){} usage. their explanation is code should never reach melting point no matter what the situation is. is this advisable?

I think it often is, yes. This is the sort of thing I was talking about in my first post above, third paragraph. I don't agree with the "no matter what the situation is" however, as there are definitely cases where "catch (Exception e)" adds no value at all, just minor code bloat. But in most programs that are intended to be run by a non-programmer, there is at leaast one point in the system where it's worthwhile to have a "catch (Exception e)" (or RuntimeException or Throwable) to provide a layer of insulation between your own imperfect code and the refined sensibilities of your customers.

Stanley Walker wrote:and also what would you guys suggest, should i throws Exception @ method definition or individually catch the exceptions. i prefer catching exceptions but is it a good programming practice?

Eh, depends on the situation; both are common. Personally I tend to declare exceptions as thrown much more often than I catch them, but I do both.
Billy Korando
Greenhorn

Joined: Sep 18, 2009
Posts: 15
Stanley Walker wrote: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.


As other have stated in most cases the answer is no. However the more germane question would be, what exactly are you going to do when you catch these exceptions and/or could the system recover from the error?

In general you should not use exception handling for validation either. There is quite a bit of overhead involved with exception handling (system writing the stack trace) and it is much better to write
<code>
if(foo == null)
System.out.println("You have to enter something");
</code>

Then catch a NPE.


Check out my blog on software development: http://www.turnleafdesign.com
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39834
    
  28
Billy Korando wrote: . . . better to write
<code>
if(foo == null)
System.out.println("You have to enter something");
</code>

Then catch a NPE.
Please use the CODE button rather than writing the tags by hand; as you see you have misspelt them.

I think you have another misspelling in that quote; I think you meant "Than" not "Then." It makes the meaning completely different.

If you have a situation where a null can be passed and you can backtrack and get a real input, then a foo == null test (or foo != null) test is useful, saving the trouble of an Exception. I think that is what you meant, and I agree with you. If you are having null passed to a method, the Exception will prevent the application completing its testing, so whoever is using the method knows to alter their code.

There are other situations where a reference may be null, eg the "leaves" in a tree data structure, or a Reader reference in the finally block if an Exception occurred earlier. In those instances a test for nullity is also necessary.
Rahul P Kumar
Ranch Hand

Joined: Sep 26, 2009
Posts: 188
I've not read the full conversation. But I'm putting my point forward about runtime exceptions. If it si repition please execuse me.
See, if you will not catch them, in runtime they will show up. Now in a live project yopu don'[t want this situation. you need to catch them and always print stack trace, that is where there real values lie. So, catch clause not only saved your face, it gave you invaluable suggestion to correct your code. During initial coding you might not be knowing that a nullpointer may come at certain point.
 
Consider Paul's rocket mass heater.
 
subject: Exception handling