• 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

Exception handling

 
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 874
Android VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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}
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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

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

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
Posts: 101
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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

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.
 
Campbell Ritchie
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Beware the other head of science - it bites! Nibble on this message:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic