When to use multi-catch and when to use rethrow? - java

I'm very uncertain about this two topics. I know that i should use multi-catch for exceptions which need to handle the same way. But for what purpose do i really need something like that.
private void something(String name) throws IOException, RemoteException {
try {
...
} catch (Exception ex) {
... // do something
throw ex;
}
}

You can do it if you consider for this method that any exception thrown during its execution should be handled in the same way and you want perform a task before letting propagate the exception to the client
For example, suppose you want to do a particular processing when the exception happens such as logging the information. So you catch it to do this task.
Nevertheless you consider that the caught exception is a problem and that logging it was not a "real" handling of the exception. So, you let it propagate by rethrowing it.

You'll need rethrow in following situations
You want to preprocess something before letting the exception leave the method. However, if you don't care about the type of the exception then preprocessing can be done in the finally block as well.
You're trying to convert the checked exceptions into unchecked exception. In that case you'll be catching all the exceptions as catch(Exception ex) and rethrowing them as throw new RuntimeException(ex).
You want your custom exception to be thrown instead of in built ones. So you'll catch all the exceptions and then create your own exception object preferably unchecked one and throw that. Many APIs do this, for example Spring converts untuitive JDBC exceptions to Spring custom exceptions.
This one is kind of like preprocessing. You want to keep track of all the exceptions thrown by creating an ArrayList or something, so that at the end of a program with multiple steps you know which steps throw exceptions. I have seen this one being used in Talend generated Java code.

ReThrow
Whenever you want to notify caller method about exception, you catch and rethrow exception.
Say some method callSomething() is calling your method something(). If any exception occurs inside something (), it will just catch exception, so application doesn't fail, and rethrow it to the callSomething() method. Then callSomething() will notify client about internal error.
Other example is, in MVC pattern, request submitted by client is served by some method from controller based on request mapping. Controller will call service, and service will interact with some method of dao. If some exception occurs in DAO, then DAO will rethrow exception to service, service will rethrow to controller, and it is controller which will notify client about error message.
This is known as Exception propagation in java. An exception propagates from method to method, up the call stack, until it's caught.
Multi catch
If you want to perform same action for multiple types of exception, then you use multi catch.

Related

Transforming Exceptions thrown from an external library in a centralized way

I would like to ask a code style question around Java Exceptions. I am using Java to call a C/C++ library using JNI. The convention in the library I am using is that most of the methods I can call will throw the same exception type for all errors. Let's call that a LibException. Now LibException is really a wrapper exception for a multitude of errors that can come up ranging from authentication problems, connection problems or more serious problems like corrupt input etc. LibException also contains an error code int as well as the error description string.
Even more confusingly LibException can also wrap one of my own exceptions if I throw it at the library in a callback! What I mean by that is that I sometimes provide a callback method, it is called by the library and I sometimes have to throw an exception in the callback. In that case the library picks up the exception, wraps it up in a LibException and throws it back at me in the original method call.
I would like each of the underlying problem to be handled differently. Authentication problems need to be shown to the user so he can retry, users should be notified of connection problems, but more serious problems may have to trigger my diagnostics report system (an automated mechanism that can send me parts of the logfile for debugging) and of course any exceptions I throw towards the library in the callback need to be rethrown as the original exception type.
Since I am calling different methods at multiple locations, I thought it would be a good idea to put some structure around the exception handling of LibExceptions. This is to avoid code repetition but most importantly to make sure that the different exception types are handled properly and that future me does not forget to, for example, notify the user that authentication failed.
I have tried a bunch of approaches but I am not entirely happy with the code structure I get so I would like some ideas on best practices from the community.
Static method that includes logic to sort the exceptions and throw a bunch of other exceptions
public static void handleException(LibException e) throws AuthenticationException, ConnectionException, SeriousException, MyException (MyException would be my exception that I throw in the callback)
+ve This works well in that it forces the handling of all the thrown exceptions.
+ve If a new exception type is added, the compiler would force me to handle the new exception
-ve Even though handleException() is a method that always throws an exception, the compiler (rightly) does not know this. This means that if we use handleException() in a method that has to return something, the compiler complains that a return type was missed. To make the compiler happy I have to throw another exception right after calling handleException() so the compiler understands that it will not be getting a return value because an exception is definitely thrown.
-ve I don't like the line that looks like Handler.handleException(libEx) since it's not entirely obvious that it throws a bunch of exceptions.
-ve Hard to customize the exception messages with context from the location the exception occurred (i.e. which URL we could not connect to).
A method that returns an enum with the different types of exceptions that I defined. Based on the enum I can then create the different exceptions to throw.
public static ExceptionTypeEnum Handler.
+ve Since I create the exceptions, I can now customize some error messages with extra context
-ve I could still forget to handle an enum (especially if I create a new category in the future)
-ve I still need a bunch of custom code to create the exceptions at every place I catch a LibException
Similar to #2 but instead of an enum return I could have multiple methods such as isAuthenticationException(libEx) or isConnectionProblem(libEx) and then accordingly throw the exceptions myself.
-ve I would definitely forget to handle all sections properly especially if a new exception type is added later.
The exception handler could return an exception to throw up. But since we throw a number of different exceptions the getException() method would have to return the Exception base class. This means that exception handlers would have to have prior knowledge of what exceptions could be thrown and also catch the Exception class making my exception handling more difficult.
Now in case I confused everyone with this question, I guess what I am trying to find an elegant solution to is similar to the problem described on section 'Checked exceptions inappropriately expose the implementation details' on page http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html
Does the community have any other suggestions of a coding method to properly and elegantly handle these LibExceptions?

How to use throws?

I am learning Java and come across the throws keyword. I came to know that it is used for exceptions we cant handle or don't wont to handle.
Why can't we just use exception.printstacktrace? Or is there any situation where throws can perform auto exception handling or it is just a mere keyword for the reader to know that the method can throw that exception?
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.
And'throws' does not perform any exception handling it just tells to delegate exception handling to caller method as its not done in called method.
exception.printStackTrace()
or
exception.getMessage()
You can print stack trace only when exception catched. Basically java follows a rule Throw or handle with checked exceptions. Handling exception is catching them.
Also remember that some where you always have to handle your exception but you have freedom to choose where in your application flow you want to handle.
And'throws' does not perform any exception handling it just tells to delegate exception handling to caller method as its not done in called method. So that called method is aware of exception it has to handle or throw back again(but as said earlier some where it has to be handled)
PS: there is very nice question for is printstacktrace considered bad
practical usage
If you are working on enterprise applications, and any exception came in middle layers those exceptions need to propagated to controllers this is one of the practical example of throws keyword.
In such applications we write navigation logic in controller and also handle logging, so it's necessary to propagate your exception message to controller layers.
When you declare that your method throws SomeCheckedException, you require of the users of your method to handle that exception (or declare that they throw it themselves if they can't handle it). It's part of the contract of the method.
dont wanna handle? never happen, you always have to handle your exceptions. But when you throw an exception, it means that you dont wanna handle this exception in this function, and you want to deal with this in another place.
Practical Usage depends on person's requirement !
Suppose I developed an API having a method animateImages(InputStream image) Now this method will work fine if a valid image is passed but what if you pass a PDF to this method , this method fails miserably .
So if i will handle the exception , I just put a stackTrace() and log what is wrong but that is of no use for you .
I want you to know the reason and to react accordingly and send the valid Image file or whatsoever you want to do .
This is why we generally throw any Exception when we want the consumer to handle it .

Spring's implementation of Exception Handling in JDBCTemplate

I am going through a Spring book to learn Spring. Having gone through sections about the JDBCTemplate i was surprised to find that Spring handles most of the SQLException exceptions differently.
For example, all checked exceptions are converted to unchecked exceptions. What exactly is the benefit of this?
In my experience, the majority of SQL exceptions should be handled. For example, we have an application that talks to an Oracle PL/SQL procedure. The call to the PL/SQL procedure can return an ORA-01403: no data found exception. This kind of exception is one that you usually recover from by displaying an error message to the user. e.g. A search result did not return anything.
How would this kind of a checked exception be handled in Spring if all exceptions are unchecked i.e. Spring wont force you to handle them?
I know that you can catch RuntimeExceptions but i quite liked the idea that you are forced to handle checked exceptions. What benefit does converting some of the checked exceptions to unchecked exceptions provide?
Yes, the exceptions should be handled, but in Spring design, on higher level then the each DAO method. In fact the design where in every method there is SQLException handling is unclean copy-paste design, and when you change something, you must apply the change in every place.
There are various demands, and various places where you handle unchecked exceptions. One of these are aspects, where you can for example convert Spring's exceptions to your exceptions (uncatched exceptions need not be declared in method signature, so this convertion is very elegant). In REST method you can add generic handler that will return the error responce to the caller, and you write exception handling in only one place. In JSF/JSP based technologies you can add own error page whenever error occures.
Some people don't like checked exceptions, as they force you to do some exception management. I guess the Spring guys are of this kind.
Personally I prefer to do things as they were intended to be made:
try {
// execute some SQL
} catch (SQLException ex) {
if (ex is an expected condition) {
// deal with it: for example with a "no data found" condition
// this might mean returning null, or throwing some kind of business exception, such as
// NoEmployeeFoundException, or whatever
} else {
// this is a programming / environment error
// throw as unchecked exception
throw new RuntimeException(ex);
}
}
Of course the downside of this approach is that is more work. The upside is that you have explicitly stated in code which are the "expected" circumstances and which ones should not happen ever.
The benefit is not being forced to catch or declare them.
I'm not convinced that not finding data during user searches is exceptional, particularly at the SQL level. Turning that into a checked exception amounts to using exceptions for generalized flow control. I would consider that an anti-pattern to be avoided; YMMV.
Many SQL-related errors are code-related; IMO it's better to fail fast--during development.

Java: Exception Handling

Is there any reason for not converting the following code
try {
// Do something
} catch (XException e) {
e.printStackTrace();
} catch (YException e) {
e.printStackTrace();
} catch (ZException e) {
e.printStackTrace();
}
to this:
try {
// Do something
} catch (Exception e) {
e.printStackTrace();
}
I know the 2nd one catches all kinds of Exceptions, and I don't mind that. And let's say I want to handle all exceptions in the same way. Is the performance difference considerable?
The Java try/catch mechanism has been so highly tuned in successive JVM's that their performance is never something you should be explicitely worried about. Rather, you should be coding those blocks according to whether you need to handle the caught error scenarios in different ways. In your example you are just printing a stack trace so it is not beneficial to catch the specific errors - but your use case will actually determine wether you should be rolling up or down for these try/catch blocks.
This separation is only because you would be able to perform different task for different exceptions. Like if you receive parse exception and you get IO exception so you would know exactly what to do with each exception.
In newer version this blocks has been minimized with multiple exception in on block which will help the coder and increase the readability. e.g.
try {
// Do something
} catch (XException | YException | ZException e) {
e.printStackTrace();
}
I wouldn't worry about performance at the moment (unless you know it's a real issue).
You may want to convert for readability (if the same action is performed for each type of excpeption), but don't forget that catching Exception will catch lots of other stuff besides XException, YException, ZException. Is there a useful base class for those, and can you catch that instead ?
Occasionally you may want to perform different actions on different exceptions.
Even if you don't you still help other programmers see the complete picture rather than hiding it in one big Exception; which also happens to catch all Runtime exceptions.
The main reason you catch the exceptions separately is you may want to do something different based on which exception has been thrown. For example when parsing a file, you may want to throw a FileNotFoundException, or an IndexOutOfBounds exception. One tells you you cannot find the file to parse, while the other tells you there was a problem during the parse itself. It's much more informative to handle these separately as they are entirely different problems. For example the end user could receive different error messages based on the exception thrown.
There is a difference in catching RunTimeExceptions like NullPointerException. Those will be caught in the second case but not in the first.
In the vast majority of situations you want exception handlers to be as specific as possible so that your code is resilient and adopts an appropriate recovery strategy in the event that an exception occurs. Taking a general approach to exception handling is unwise as the handler must react to any exception possibility which this can result in code being more error-prone when unexpected exceptions are caught which the handler was not intended to handle. In essence exception handlers with the clause catch (Exception e) is the lazy approach.
In my experience the motivation for placing an exception handler around a block of code is to catch a specific exception or set of exceptions. Therefore at the time of conception you know the exceptions you want to catch anyway, why generalise and use the Exception class?
I'd advise reading two things to gain appreciation for specific exception handling:
Effective Java Second Edition - Joshua Bloch : Chapter 9
The Java tutorial on Exceptions : Advantages of Exceptions
IMHO it is just a question of handling all errors the same way or some in a different way.
First one is useful when you want to handle different exceptions in different ways and in second case you are handling all exception in same way. Use second way when you perfectly don't know which exception will occur and if you know you can use the first one.
Not much difference from a technical perspective. The second version will catch all XYZ exceptions plus any RuntimeException that may be thrown in the try block. Check, if that is OK.
If the catch handlers all do the same for any thrown exception, then I see no problem with grouping them. Although it is not very common (in production code) to have equal catch handlers, usually they do different things or log different messages.
Reason is to handle different exceptions for ex. for a sql exception you may want to rollback the transaction but for a io exception for an unfound file u may want to create that file etc.
If we consider the performance there is no difference between handling in one catch block or with multiple.
exception can occurs for many reasons
A file that needs to be opened cannot be found (fileNotFoundException or InputStreamExcep)
A user has entered invalid data.
network connection has been lost or the JVM has run out of memory.
Types of exceptions:
Three Kinds of Exceptions are:
Checked exception:
A checked exception is an exception that a user error or a problem which is not foreseen by the programmer.
Example:if a file is to be opened, but the file is not found, an exception occurs. These exceptions cannot be ignored at the time of compilation.
Unchecked exceptions: A runtime exception is an exception that occurs that probably ignored by the programmer.It is also known as runtime exceptions.these are ignored at the time of compliation.
Errors: problems that arise beyond the control of the programmer.
Example, if a stack overflow occurs, an error will arise. These are ignored at the time of compilation.
Catching Exceptions:
Byusing try/catch, we can handle the exception.try block is placed around the code that might generate an exception.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Multiple catch Blocks:
A try block can be followed by multiple catch blocks.

use of rethrowing checked/unchecked exceptions?

What is the use of rethrowing checked and unchecked exceptions?
If you want to execute some code when a problem happens without hiding the problem.
For example, let's say you want to rollback changes if an exception occurs while writing to a database:
try {
writeToDatabase();
} catch(Exception ex) {
rollbackChanges();
}
If you use this code, the calling function will never find out that an exception occurred.
Instead, you should write
try {
writeToDatabase();
} catch(Exception ex) {
rollbackChanges();
throw ex;
}
To be somewhat blunt: to use exception handling.
Consider this, before exceptions (or, before a developer understands how to properly use exception handling) programmers would return error codes like -1 or null if something 'went wrong'. With that in mind, how would you tell something several methods back that it failed (eg: some low level IO method in a large API failed)? You could either string a lot of return nulls/ or -1's together, or just throw an exception so that it migrates back up to somewhere where it should be caught, even the JVM itself if need be as this exception might something you cannot recover from.
So basically, you would rethrow an exception if you are unable to write catch logic that can truly recover from the thrown exception. This is often the case in Java because Java forces you to catch almost all of its Exceptions since most everything is a checked exception.
As for rethrowing checked vs unchecked... Often times I will throw a new unchecked exception (RuntimeExpcetion) from inside a checked exception back up to the container when doing J2EE applications. The container has a default way of handling exceptions and showing the user a default error page. This comes from the Aspect Oriented paradigm. I also wrote about how to do this here.

Categories