Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am working on a Java application, and I see that Run time exceptions are handled in many places. For example,

       try {

                  //do something

        }catch(NullPointerException e){

            return null;

       }

My questions is, when is it a good practice to handle Runtime exceptions? When should exceptions be left unhandled?

share|improve this question
6  
-1: There's no single answer to a question this broad and vague. It's impossible to provide a single answer to a question so unfocused as this. This question is awful. Please provide specific examples of where you have doubts. –  S.Lott Jul 11 '11 at 11:23
    
@S.Lott I kind of disagree in this case as it seems there is a subset of programmers that have it in their head that this is the case with no "Good" Rationality. –  Chad Jul 11 '11 at 19:04
1  
@Chad: "this is the case with no "Good" Rationality". That may be true. But the only possible answer has to be "it depends". Therefore, the question seems faulty. –  S.Lott Jul 11 '11 at 19:06
add comment

5 Answers 5

up vote 12 down vote accepted

It depends.

For example, Integer#parseInt throws NumberFormatException (which is a RTE) if the provided string can't be parsed. But surely you don't want your app to crash just because the user wrote "x" to a text field that was for integers? And how do you know whether the string can be parsed, unless you try to parse it first? So in this case, the RTE is just an error signal that should cause some kind of error message. One could argue that it should be a checked exception, but what can you do - it isn't.

share|improve this answer
3  
+1 for "it depends". –  user1249 Jul 11 '11 at 9:46
2  
I agree with "It depends", but your parsing example seems to be rather a case of bad API design. Integer#parseInt should really return a Maybe<Integer> instead and not throw any exception at all. –  Jörg W Mittag Jul 11 '11 at 12:12
1  
@Jörg W Mittag: I agree that it's bad API design, but it's the real world we have to deal with. How to properly handle throwables / return values depends on how the world actually works, not on how it optimally should work :-) –  Joonas Pulakka Jul 11 '11 at 12:47
    
The point here is, you can do something meaningful for an anticipated condition (user input not integer). Just swallowing NPE is bad style and will just cover up existing programming errors. –  Jürgen Strobel Jun 12 '12 at 14:01
add comment

NullPointerExceptions are usually the sign of a missing null check. So, instead of catching it like this, you should add the apropriate null check to be sure to not throw the exception.

But sometimes, it is appropiate to handle RunTimeExceptions. For example, when you cannot modify the code to add the null check at the appropriate place, or when the exception is something other than a NullPointerException.

Your example of handling exceptions is terrible. Doing so, you lose the stack trace and precise information about the problem. And you are actually not solving it as you will probably trigger another NullPointerException in a different place, and get misleading information about what happened and how to solve it.

share|improve this answer
1  
I'd like to add that a null check is a better decision performance-wise. –  Mahmoud Hossam Jul 11 '11 at 10:12
    
...still, if you're making dozens of allocations that "should never fail" around one place, adding null checks for each of them may ridiculously obfuscate the code. A catch-all exception (that WILL handle the situation gracefully, not just return null;) will be a better solution. –  SF. Jul 11 '11 at 13:26
    
You probably are confusing java with something else (C++ for exemple). When an allocation fails, you get an OutOfMemoryError or something similar, never a null pointer. Hidding a null return instead of an exception is hidding the error waiting for the code to explode somewhere else. –  deadalnix Jul 11 '11 at 13:34
    
new throws std::bad_alloc in C++. –  R. Martinho Fernandes Jul 11 '11 at 14:43
    
Assuming that the new operator isn't overloaded, which is common practice. In C++, anything can happen ;) But OK, let's say C's malloc. The important point was that you never got that in java. –  deadalnix Jul 11 '11 at 14:51
show 4 more comments

Exceptions should be just that.. exceptions. Best practice when using exceptions is to use them to cover the situation in which something contrary to what you would expect to happen happens. The classic example is the FileNotFoundException which gets thrown when a file simply isn't there. If you're testing the existence of the file, then you use File.exists() since you're simply prodding with a 10 foot stick to see if you hit something.

You could technically accomplish the same results by surrounding it in a try catch and using the file as if it existed, but A) exceptions are generally costly resource-wise and B) programmers are going to assume you meant the file to exist if it was in a try catch, which adds to the overall confusion of a program.

There are many situations in which I'll write a method which fetches some value from a database. A thousand things could go wrong, and seeing how I only need one small piece of information, it's inconvenient to surround the call with a try catch list that contains 5 various exceptions. So, I'll catch exceptions in the fetch method. If something goes wrong, I take whatever appropriate action to close the database connection or whatnot in the finally clause and return null. This is good practice not only because it simplifies your code but also because "null" sends the same message you could have gotten from an exception.. that something didn't go as planned. Manage exception specifics in the fetch method, but manage what to do when things don't go as planned in the receiving end by checking to see if the result was null.

For example:

Integer getUserCount() {
   Integer result = null;
   try {
      // Attempt to open database and retrieve data
   } catch (TimeoutException e) {
      logger.error("Got a watch?");
   } catch (MissingDatabaseException e) {
      logger.error("What are you smoking?");
   } catch (PermissionsToReadException e) {
      logger.error("Did you *really* think you were getting away with that?");
   } catch (PressedSendButtonToHardException e) {
      logger.error("Seriously.. just back away from the computer... slowly..");
   } catch (WTFException e) {
      logger.error("You're on your own with this one.. I don't even know what happened..");
   } finally {
      // Close connections and whatnot
   }
   return result;
}

void doStuff() {
   Integer result = getUserCount();
   if(result != null) {
       // Went as planned..
   }
}
share|improve this answer
3  
If you use File.exists() and rely on the result, a race condition could happen if the file is deleted right between File.exists() and File.open(). If this triggers a security-critical bug, an attacker could cause this condition on purpose. Because of this, it's sometimes better to keep the operation atomic, i.e. try it and catch the exception. –  user281377 Jul 11 '11 at 10:51
1  
Also, there are files that must exist for the running of the application. Those would be exceptional conditions. If there's a file that you must have in order for the application to function, then there's no reason not to read from it and then handle the exception for the exceptional case. I believe it makes the intent more clear. –  Thomas Owens Jul 11 '11 at 11:05
    
This a bad decision to return null. It will result in NullPointerException at some point and will be really hard to debug what went wrong. Because somebody WILL at some point forget the null check. –  deadalnix Jul 11 '11 at 12:17
    
@deadalnix: I could argue that you could just as easily forget to surround with a try-catch otherwise. Difference is a matter of style, not functionality. –  Neil Jul 11 '11 at 13:37
    
@ammoQ: I disagree. I think you should use File.exists() and under the rare circumstance that it gets deleted before you use it, an exception is more than appropriate. The difference is where you keep your catch. Simply have a blanket exception catcher for unanticipated errors in order to log and report it. –  Neil Jul 11 '11 at 13:40
show 4 more comments

I handle Expected exceptions where I expect them. (Like DB read/write errors). Unexpected exceptions I bubble up. Somewhere else may be expecting the exception and have the logic for it.

share|improve this answer
add comment

yes you are correct handling run time exceptions is not a good practice.The reason is that it is considered to costly/ memory intensive.

share|improve this answer
4  
Hi prassee, can you elaborate on your answer? One-liners that aren't backed up with facts, references, or experiences aren't very helpful. –  user8 Jul 11 '11 at 9:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.