This question already has answers here:
When is it OK to catch a RuntimeException
(10 answers)
Closed 7 years ago.
While programming in java is there any time that I as the programmer should be considering to catch RuntimeExceptions ?
You catch RuntimeException for the same reason that you catch any exception: you plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to rethrow with a different exception type.
Catching and ignoring any exception, however, is extremely bad practice.
This is what I can think of.
If you want to show a nice message to the end user in case something has gone wrong, catch the RuntimeException and log it. Then show some nice message in the screen instead of a blasting error.
To wrap the framework specific CheckedExceptions to application specific RuntimeExceptions.It is preferred to use the RuntimeException as your custom exception as told here.
Based on user validation if want to show custom message to the user then go for RuntimeException.
Wrap your custom message in then throw it.
throw new RuntimeException("Invalid userName/Password !");
Basically, the only time you would want to catch one is when you cannot allow your application to blow up. This is a good article describing this in much more detail, but here is a quote that sums it up:
"If a client can reasonably be expected to recover from an exception, make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception".
Since unchecked exceptions are basically just bugs in your code and by really should only be thrown where there is nothing that can be done about them, the only real time that you would want to catch one is when you cannot allow your application to blow up.
Yes: whenever you can and want to recover from them.
Many common exceptions inherit from RuntimeException and each may or may not be recoverable depending on the particular circumstances. The RuntimeException class itself does not imply that the exception must or must not be caught.
For example, you may have a library method which throws IllegalArgumentException on certain inputs. If applicable to your program, you could catch this exception and recover in some way, for example by trying a different input, or explaining to the user why the operation cannot continue.
Related
This question already has answers here:
When is it OK to catch a RuntimeException
(10 answers)
Closed 5 years ago.
Recently I was at an interview and the interviewer asked me regarding exception handling. I gave the typical checked unchecked answer. Then He asked me should you handle runtime exception ? I said no and then it was asked that if we get a NullPointerException suppose, will you send the same to the user ?
I got confused. So what I am looking for is that, should we catch runtime exceptions or not ?
If Yes, How can we do that ?
If No, then do we show java.lang.nullpointerException to the user ?
Thanks in advance.
The best way to handle any predictable RuntimeException is to catch it and produce user-friendly information about what happened with probable causes and what the system expects the user to do next.
Suppose if you have a project that provides the user with a UI based calculator. Now, what should ideally happen if the user enters a 'division with zero' instruction? Say if you are not checking for the 0 denominator (which of course is not advisable), your program will throw an ArithmeticException. How should you handle it? You should catch it and let the user know that he has entered an input which the system was not expecting, i.e.
You cannot divide by zero. Please enter a non zero denominator!
If it is an API and is to be consumed by another application, what I would do is to wrap the runtime exception into a customized API specific exception and throw it from there, so that the implementor can use the information and handle it in a suitable fashion. e.g.
public int divide() throws InvalidArgumentsException
Your average user isn't going to know what the NullPointerException is or how/why it happened. You would usually present the user with a more friendly error, perhaps with an error code they can provide to help identify the error.
The application may also save the NullPointerError along with the stack trace to a file so a developer can see exactly where the error occured.
You can catch RuntimeExceptionclasses in your Application by implementing a UncaughtExceptionHandler:
Thread.setDefaultUncaughtExceptionHandler(Thread t, Throwable e) -> {
// log Exception to file, send to server ecc, you can check which exception was thrown and act accordingly...
// you can still re-throw the exception here as if this block did not exist
});
This method should catch all uncaught Exceptions, even those that were thrown by other Thread instances, so it's safe to just use one implementation.
You question:
should we catch runtime exceptions or not
It depends; you don't want a whole Banking Application Server crash, just because it could not find a file in the file-system.
At the same time, RuntimeException's usually happen because there is a flaw in the code. NullPointerException's can be avoided, as well as many others...
When I throw an exception from the package in which I handle the database, in the package in which I handle the UI, should I throw the same exception or create another?
The UI package should know the exceptions of the package which I handle the database?
We as programmers want to write quality code that solves problems. Unfortunately, exceptions come as side effects of our code. No one likes side effects, so we soon find our own ways to get around them. I have seen some smart programmers deal with exceptions the following way:
public void consumeAndForgetAllExceptions(){
try {
...some code that throws exceptions
} catch (Exception ex){
ex.printStacktrace();
}
}
What is wrong with the code above?
Once an exception is thrown, normal program execution is suspended and control is transferred to the catch block. The catch block catches the exception and just suppresses it. Execution of the program continues after the catch block, as if nothing had happened.
How about the following?
public void someMethod() throws Exception{
}
This method is a blank one; it does not have any code in it. How can a blank method throw exceptions? Java does not stop you from doing this. Recently, I came across similar code where the method was declared to throw exceptions, but there was no code that actually generated that exception. When I asked the programmer, he replied "I know, it is corrupting the API, but I am used to doing it and it works."
Please visit here for more details.
To keep your layers tightly coupled, I recommend to abstract your Exceptions (if there isn't a fitting standard exception). With abstract I mean that you could wrap database-dependent exceptions like SQLException into a PersistenceException or sth. like that. This way you can easily change your layers without having to worry about changing code of the layers above.
You should then only catch and handle the exception if you can handle them, e.g. propagate it to the user in you GUI. Otherwise you should throw them to the next caller, until it is handled on a higher level.
You should avoid recreating new exceptions on their way up, that wouldn't add any information in most cases.
You should throw an Exception that makes sense. More importantly you should not throw an exception that doesn't. Exceptions represent error states that you cannot easily recover from, meaning that if you have code to handle things like missing files, it should not throw an exception. You should only throw an exception when something unexpected happens.
As exceptions propagate up through your stack, they should be diversified, depending on what part of the code they where caught in.
For instance your persistence framework may throw an SqlException, your DAO Layer may re-throwthis as an IllegalArgumentExection, or ObjectNotFoundEception, your Service Layer may throw a MalformedRequestException, an AccessDeniedException or a DeviceNotEnrolledException. Lastly your UI may display this to the user in any number of meaningful ways.
I recommend putting the exceptions where it relates the most. You should have different exceptions that handle the code in different types of situations. The UI is going to have different types of exceptions it should handle than the database.
Use pre-defined exceptions where it makes sense, you could also make your own exceptions and put them in both packages if need be.
Design it so that the code can be handled in a way where the catch statement is easy to logically locate and the catch statement handles the code and can do some sort of recovery after being passed up the hierarchy.
The type of situation we are concerned with the most are checked exceptions. These are problems that we can anticipate and catch and try to make a recovery. Make sure you aren't using too many of these! They are costly to resources!
Of course exceptions should be handled at the appropriate level you think and appropriately. Suppose you don't know what to do with checked exception and you wrap it in appropriate custom unchecked exception just to propagate up to the top level (it is supposed that you don't handle that wrapped exception and other possible unchecked exceptions at some medium level up apart the level which original exception occurred at (because of you don't want or don't know how)). Go further, All unhandled exceptions (unchecked and checked, that were wrapped in unchecked) reached the top level (main method, controller of webapp, etc); of course I should something to do. All I want to do is to notify the developer by using log entry that something was wrong and communicate the user that his request can't be serviced correctly (using different messages in dependence of what message is appropriate for that exception). To do that, I use in catch block RuntimeException (if it catches not custom unchecked exception, I’ll send the user a message "Serious problem occurred" or something like that; probability that such not custom unchecked exception will be cached greater than zero, and you must communicate about it). Some articles (first, second) advise not to catch instances of subclasses by super type in catch block (or it is only related to checked exceptions?). If I used accurate types of exceptions in catch blocks I would miss some unchecked exceptions and application would crash (and of course there would be duplicate code snippets in those catch blocks performing logging and notifying the user). As an example, I can provide the snippet that is constructed in jsp translation phase and uses super type to catch instances of subclasses of that supertype
// some code
try {
// body of translated JSP here...
} catch (Exception e) {
out.clear();
pageContext.handlePageException(e);
}
// some code
My question: is this concept is correct to use RuntimeException in catch block at the top level to report about all problems to developer and communicate the user about all occurred problems? Of course, exception handling in this case is reduced to just notifying developer and user that the problems occurred and there are no recovering strategies. Maybe it is hard to call that concept as exception handling. Please correct me and I appreciate any ideas about that concept.
I think in your situation this is the right way to go.
You don't want users at best to be confused by seeing a stack trace and at worst revealing possible security issues by seeing back-end server names, database credentials, database schema etc.
Your catch should hide this information from users and print a helpful error message to the user instead so at least they know what the problem is.
My only concern with your code is perhaps you should catch RuntimeException separately from Exception (or even Throwable)
try {
// body of translated JSP here...
}catch(RuntimeException re){
//something unexpected
//handle here
} catch (Exception e) {
//checked exception
//handle here
}
Wrapping all your Exceptions with a RuntimeException, and handling them in your main method, or wherever you define as being your top level, is a very bad practice. Instances of Exception should be handled as close as possible from where they were thrown, as they exist to identify an error from which you can recover. For instance, if you are trying to open a file, and get a FileNotFoundException, you should then take action on this (display an error message, add an entry in your error log, etc.).
Most of the time, RuntimeException represent programming errors (). More often than not, they indicate that the application is in an unstable state, and recovery is hard if not impossible. IllegalStateException, NullPointerException and IndexOutOfBoundsException are examples of such situations.
Now, the concept you are proposing, where all RuntimeExceptions are caught in the top-level method is not a viable solution for any software containing more than a few hundred lines of code, and a very bad practice in shorter programs.
Assume you have an application with 100k lines of code. Once an exception has been thrown, it will be impossible from your top-level method to correctly handle your exception. What should it do if it is a NullPointerException? Where was it thrown from? And what about that CloneNotSupportedException? You will end up having a top-level method dozens of pages long that will handle every possible exception, with the biggest if-then-else statement of all time.
Additionally, if you implement such a concept, you should be aware that whenever an exception is thrown, your application will go in that catch block in your top-level method. Once you have logged the error, you will never be able to return the control to the part of your application that generated the error, because you will not have the context from which the Exception was thrown.
I keep getting the dreaded java.something.someException errors while running my java app. and I don't seem to be getting the hang of what exceptions to handle and what not to?
When I read the api docs most of the functions throw exceptions like if I use I/O or use an Array... etc.
How to make a decision about what exceptions to catch and what not to and based on what parameters?
I am talking about checked exceptions here.
Short answer
Catch exceptions that you can deal with then and there, re-throw what you can't.
Long answer
It's called exception-handling code for a reason: whenever you are tempted to write a catch block, you need to have a good reason to catch the exception in the first place. A catch block is stating your intent to catch the exception, and then do something about it. Examples of doing something about it include, but are not limited to:
Retrying the operation that threw the exception. This can make sense in the case of IOException's and other issues that may be temporary (i.e. a network error in the middle of trying to upload a file to a server. Maybe your code should retry the upload a few times).
Logging the exception. Yes, logging counts as doing something. You might also want to re-throw the original exception after logging it so that other code still has a chance to deal with the exception, but that depends on the situation.
Wrapping the exception in another exception that is more appropriate for your class's interface. For example, if you have a FileUploader class, you could wrap IOException's in a more generic UploadFailedException so that classes using your class don't have to have detailed knowledge of how your upload code works (the fact that it throws an IOException is technically an implementation detail).
If the code can't reasonably do anything about the problem at the point where it occurs, then you shouldn't catch it at all.
Unfortunately, such hard-and-fast rules never work 100% of the time. Sometimes, a third-party library you are using will throw checked exceptions that you really don't care about or which will never actually happen. In these cases, you can get away with using an empty catch block that doesn't run any code, but this is not a recommended way to deal with exceptions. At the very least, you should add a comment explaining why you are ignoring the exception (but as CPerkins notes in the comments, "never say never". You may want to actually log these kinds of "never-going-to-happen" exceptions, so just in case such an exception does happen, you are aware of it and can investigate further).
Still, the general rule is, if the method you are in can't do something reasonable with an exception (log it, rethrow it, retry the operation, etc.) then you shouldn't write a catch block at all. Let the calling method deal with the exception. If you are dealing with checked exceptions, add the checked exception to the throws clause of your method, which tells the compiler to pass the exception upwards to the calling method, which may be better suited to handle the error (the calling method may have more context, so it might have a better idea of how to handle the exception).
Usually, it is good to put a try...catch in your main method, which will catch any exceptions that your code couldn't deal with, and report this information to the user and exit the application gracefully.
And finally, don't forget about finally
Also keep in mind that even if you don't write a catch block, you might still need to write a finally block, if you need clean-up code to run regardless of whether the operation you are trying to perform throws an exception or not. A common example is opening up a file in the try block: you'll still want to close the file, even if an exception occurs, and even if your method isn't going to catch the exception. In fact, another common rule of thumb that you might see in tutorials and books is that try...finally blocks should be more common that try...catch blocks in your code, precisely because catch blocks should only be written when you can actually handle the exception, but finally blocks are needed whenever your code needs to clean up after itself.
I highly recommend chapter 9 (Exceptions) in Joshua Bloch's Effective Java, 2nd Edition for these questions.
A general rule of thumb is to handle those exceptions that you can do something about and don't handle those that you can't. In the cases where you don't handle an exception the caller is expected to handle them. If you're writing a framework or a library usually you'll end up wrapping low level exceptions like SQLException in a library or framework specific exception to abstract away the lower level details.
For example, if you're writing a method that writes to a file on disk then you should probably handle FileNotFoundExceptions since you can create the missing file, but if you run into problems creating the file or writing to it then you should probably let the caller handle it (after performing whatever cleanup work needs to be done).
These are my personal findings:
You need a try {} catch (Throwable o) {...} in your main routine so any unexpected exception can be caught, logged and the user told.
Checked exceptions are checked because you need as a programmer to make a decision what to do when they happen. Remember, one decision might be just to say "ok, time to crash".
If you end up with a fatal situation with a checked exception where all you can do is crash, then "throw new RuntimeException("reason", checkedException);" so the handler above have something to log. Include value of important local variables - remember some day you will have to debug a situation where the only thing you have is the stack trace.
Never, ever catch an exception and just ignore it. If you have to then you must document why you are allowed to break the rule, and do it right there, in the catch block.
And a hint that will help you some day: When you crash, provide a simple means to let the user seeing the message email the stack trace to you.
EDIT: Do not be afraid to create new exceptions if the ones available does not completely cover what you need. This allows you to get better naming in stack traces and your error handling code can differentiate between different cases easily. You may want to base all your own exceptions on a common base class ("OurDomainException") so you can use the base class in catch clauses to see if what type it is.
Having coded in Java for a few years, I agree that it is easy to get annoyed by writing endless try-catch blocks.
A good way of coding fast is to catch specific exceptions in as low level as you can, and catch the base Exception at the outermost level (in main()) just so that you can write a generic error message instead of letting the program crash.
This lets you have a running code pretty fast, and then you can take your time to add specific exceptions in various layers with their handling logic.
Catch checked Exception, do not catch RuntimeException. Try to catch specific Exception, try not to catch by generic java.lang.Exception.
Module boundaries
I catch exceptions for cleaner module boundaries, too. For example if there is a SQLException thrown that I can't handle I'll catch it nevertheless and throw my own descriptive exception instead (putting the SQLException as cause). This way the caller doesn't have to know that I'm using a database to fulfill his request. He just gets an error "Cannot handle this specific use case". If I decide to fulfill his request without database access, I don't have to change my API.
As a rule of thumb I catch exceptions where I will be able to do something with then, or where I want the exception to stop moving up. For example, if I am processing a list of items, and I want the next item to be processed even if the others fail, then I will put a try...catch block around that item processing and only in there. I usually put a try...catch(Throwable) in the main method of my program so I can log errors like a class not found or similar stuff.
I don't put a try...catch block in a method if I will not know what to do with that exception. If you do, you will just bloat your code with lots of exception handling code.
when an exception occurs that a method is unable to handle - does the program terminate and show the error number ? where does the error number and information about the error come from ? should the programmer while coding have an idea what kind of exception might occur. if so why does'nt he ensure that exception does not occur .
If you are using Java APIs, the exceptions that each method throws are documented.
When the program terminate, it shows an stacktrace of the methods calls that caused that specific problem.
Check the lesson on Exceptions from The Java Tutorial. You can learn much more reading there than reading my answer here :)
There are 2 main types of exceptions in Java:
- checked
- unchecked
unchecked exceptions are further broken into RuntimeException and Error.
RuntimeExceptions are programmer errors (ArrayIndexOutOfBoundsException) and Errors are things that are problems in the VM (OutOfMemoryError).
You should not catch RuntimeExceptions - you should fix your code so it does not throw the exception.
You should not catch Errors since the VM is likely in a state that you cannot do anything to recover from them.
If your main does not catch an unchecked exception it will crash.
Java Exceptions bubble-up to the point where someone catches them, or to the point the program exits.
In the real-world, when many frameworks are used, exceptions never bubble-up to the top. They are caught and reported (printed on console). Catching exceptions is done by the try { } catch(..) { } block.
There are two types of exceptions - checked and unchecked. The checked exceptions must be declared in the method signature (unlike the unchecked)
should the programmer while coding
have an idea what kind of exception
might occur
Yes, but no one's perfect.
why does'nt he ensure that exception
does not occur
In exceptional circumstance, you WANT an exception. You do not want to ignore the exception.
For example, suppose that your program creates a file to save user settings. If for some reason
the file creation fails (which your program has no control over, it's the Operating System's job), you do not want to go on like nothing happened. You want there to be an exception, so that whoever or whatever function called that function knows about this problem, and can do something, e.g. inform the user.