use of rethrowing checked/unchecked exceptions? - java

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.

Related

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

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.

Is it possible to switch all exceptions to generic messages?

In Java, is it possible to force all exceptions to return a generic message?
(that is, uncaught exceptions.)
Context: When testing applications, I often encounter applications which leak information through exceptions. I would like to recommend a way to force exceptions to give a generic message.
Example: Give bad input to application. Application dies, giving error message from exception.
The most generic way is:
try { ... } catch (Throwable t) { ... };
Sometimes I use this method when there is an exception generated and I don't know where it comes from.

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 exceptions and inner exceptions, am I doing this correctly?

I'm validating a xml against a xsd, and I'm finding that there are many cases where exceptions have to be handled.
I believe these are called checked exceptions in java?
SchemaFactory sf = ....
Schema schema = sf.newSchema(...) // SAXException has to be handled
Validator validator = ...
validator.validate(xmlFile); // IOException has to be handled again
How should I be writing this code block?
Do I use try/catch nested inside a try/catch?
try {
SchemaFactory sf = ....
Schema schema = sf.newSchema(...) // SAXException has to be handled
Validator validator = ...
validator.validate(xmlFile); // IOException has to be handled again
} catch (SAXException e) {
// handle SAX error
} catch (IOException e) {
// handle IO error
}
Do I use try/catch nested inside a try/catch?
IMO, no.
try {
//...
} catch(SAXException e) {
//handle SAXException
} catch(IOException e) {
//handle IOException
}
I think the code looks cleaner like that than with nested try/catch.
How should I be writing this code block?
It depends on whether you need to handle the exception right there, in which case you use try/catch, or if need the caller to handle the exception, in which case you should propagate it to the caller by using the throws clause.
public void validateXml() throws SAXException, IOException {
//...
Actually you are not supposed to handle checked exceptions if you don't have any recovery strategy.
Do you have another schema in case the one you use raise a Sax exception?
Do you have another validator in case the one you use raise an IO exception?
Any other recovery possible for these exceptions?
If you don't, you should probably wrap that exception inside a Runtime (unchecked) exception and let it be thrown to the top layer (where it will be catched). Eventually you can add an extra message in the wrapper class if needed to understand the problem.
Unless your program can work correctly without this sax schema (in this case you would catch Exception, to also be able to catch runtime exceptions), or your program have a recovery strategy, you are not supposed to catch an exception without rethrowing it.
If your recovery strategy fail, you can also wrap the recovery exception into an unchecked exception to let the top layer handle it (log + error 500 or something like that).
This is the principle of fail-fast.
Note that in Java there is a big controversy that exist for years about checked VS unchecked exceptions. Many influent people in Java really think introducing checked exceptions was an error.
The main reasons are:
People are lazy and tend to catch the exception in the wrong place, so that they are not bothered anymore.
People doesn't follow the sun recommandations: they throw checked exceptions just to "give a warning" at compile time for the client side of the API.
People tend to think that only methods declaring checked exceptions can raise exception, while ANY code/method CAN throw exceptions. You are not supposed to catch exception ONLY WHEN THE COMPILER SAYS SO: YOU HAVE TO THINK WHERE IT'S APPROPRIATE TO CATCH.
Are kinda agree with Bruce Eckel:
I think the problem is that this is an untested assumption we're
making as language designers that falls into the field of psychology.
You can find many links on that subject. Many java developers are not aware of this, but also many mature frameworks now mainly use unchecked exceptions (Spring, EJB3...).
Also people doing C# (no checked exceptions) and Java tend to think it's better when there are no checked exceptions.
So you may do:
try {
your code here
} catch (Exception e) {
throw new RuntimeException("optionnal message",e);
}
You can eventually use a custom runtime exception if you think it will be useful
Sun sources:
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Here's the bottom line guideline: 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.
http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html#11.5
The class Exception is the superclass of all the exceptions that
ordinary programs may wish to recover from.
Bruce Eckel (Thinking in Java book):
http://www.mindview.net/Etc/Discussions/CheckedExceptions
"Ignorable" in the previous paragraph is the other issue. The theory
is that if the compiler forces the programmer to either handle the
exception or pass it on in an exception specification, then the
programmer's attention will always be brought back to the possibility
of errors and they will thus properly take care of them. I think the
problem is that this is an untested assumption we're making as
language designers that falls into the field of psychology. My theory
is that when someone is trying to do something and you are constantly
prodding them with annoyances, they will use the quickest device
available to make those annoyances go away so they can get their thing
done, perhaps assuming they'll go back and take out the device later.
I discovered I had done this in the first edition of Thinking in Java:
...
} catch (SomeKindOfException e) {}

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.

Categories