Handling Runtime exception in Java - java

I have the following piece of code
try{//do something
}
catch (Exception e) {
log.error(e, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
the findbugs stataic analysis tool throws this warning on it
instanceof will always return true for all nonnull values in methodX, since all RuntimeException are instances of RuntimeException
what i dont understand is that its Exception which is being caught and not the RuntimeException, so why this warning ?

Perhaps, the // do something code does not throw any checked exception, so the only exceptions you can get in your try-block are unchecked ones (subclassing RuntimeException).

You could also try following code. This will be better to read and maintain.
try{//do something
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}

Probably there is no methods that throws not RuntimeException in "try" part. Therefore, you can use construction
catch(RuntimeException e)
{
//Do something
}

Try http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Throwables.html#propagate%28java.lang.Throwable%29. It does exactly what you want. Today I did the replacement for the same reason (findbugs warning), also looked the source of this method.

Related

How to re-throw a Throwable?

Consider this code:
#Test(expected = NullPointerException.class)
public void testSaveEmptyApplication() {
try {
Application application = new Application();
Application result = applicationService.save(application);
} catch (Exception e) {
if(e instanceof UncheckedServiceException) {
throw e.getCause(); // java.lang.Throwable, compiler error
}
}
}
How to re-throw a Throwable?
The problem is that testSaveEmptyApplication is not declared to throw any checked exceptions. But e.getCause() returns Throwable which is a checked exception. So what you are doing in your example code is breaking Java's checked exception rules.
If you know that the cause really is a RuntimeException, then you can do this
throw (RuntimeException) e.getCause();
Caveats:
However, if your assumption is incorrect and the cause exception's actual class is a checked exception, the above will result in a (brand new) ClassCastException which squashes the cause exception you were trying to rethrow.
The above will also break if the cause was an Error, but you could deal with that; e.g something like this.
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new AssertionError("Unexpected exception class", cause);
}
If you want to be able to rethrow checked exceptions, then they must be declared in the method signature. Once you have done that you can discriminate and throw them as per the above pattern.
This is all a bit cumbersome. But this is the price you pay for having wrapped the exception in the first place.
One solution I can think of for there is:
The catch clause to be:
try {
// ...
} catch (Exception e) {
if(e instanceof UncheckedServiceException) {
if(e.getCause() instanceof NullPointerException) {
throw new NullPointerException(e.getCause().getMessage());
}
}
}
Otherwise change the method signature like this:
public void method() throws Throwable {
// ...
}

propagating error upwards in java

I have a main class where I have something like
void FooBar(String s){
try {
parseString(s);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
context.getCounter(Counters.ERROR).increment(1); // this increment doesnt increases
}
}
parseString is
void ParseString(String s){
if (matcher.matches()) {
} else {
//throw exception
try {
throw new Exception("bad formatted N-triples");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But for some reason, the error is not propagated upwards. In my FooBar method the error counters are not incremented even if the function gets bad formatted data.
How do I propagate this exception upwards?
But for some reason, the error is not propagated upwards...
The reason it is not propagated upwards is that you caught it. Exceptions stop propagating when they are caught.
Either don't catch it in parseString, or rethrow it in the handler; e.g. e.printStackTrace(); throw e;
However, this is likely to get you into more problems, specifically because of the exception you are catching / throwing here. The problem is that Exception is the root of all checked exceptions:
Since it is a checked exception, the method parseString must declare that it throws the Exception if you want to the exception to propagate.
But throws Exception is saying that this method could throw any possible checked exception ... which makes life difficult for the caller. (Not in this example ... but in general.)
My advice is as follows:
Avoid creating / throwing Exception. Pick a more specific (checked or unchecked) exception that reflects the meaning of the "exceptional event" you are trying to report ... or implement your own exception class. In this case throwing IllegalArgumentException would probably be better, though that is an unchecked exception.
Avoid situations where you need to propagate Exception.
Be careful when you catch Exception. It catches every (non-Error) exception, including all of the unchecked ones; i.e. RuntimeExecption and its subclasses.
You either don't catch it in ParseString, or you rethrow it with throw e;
Once an exception is caught, it doesn't get propagated unless you throw it again.
Examine what you're doing here:
try {
throw new Exception("bad formatted N-triples");//You throw an exception!
} catch (Exception e) {//And immediately catch it!
e.printStackTrace();
}
Because the exception is caught, it will not propagate. Instead, remove the try/catch block and simply throw the exception:
void ParseString(String s){
if (matcher.matches()) {
//code for reasons
} else {
//throw exception
throw new Exception("bad formatted N-triples");
}
}
Note that this is actually bad practice. You want to say something about your exception, and declare it:
void ParseString(String s) throws IllegalArgumentException {
if (matcher.matches()) {
//code for reasons
} else {
//throw exception
throw new IllegalArgumentException("bad formatted N-triples");
}
}
The surrounding function should know how to cope with that exception explicitly, rather than just throwing it's hands up because it's a general exception.
You shouldn't surround your error with try/catch:
void ParseString(String s){
if (matcher.matches()) {
}
else{
//throw exception
throw new Exception("bad formatted N-triples");}
}
}
When you throw the error, it's caught in the catch statement within parseString method, which is why isn't isn't propagated to the top.
Ideally, you'd do:
void ParseString(String s) throws Exception {
if (matcher.matches()) {
}
else{
//throw exception
throw new Exception("bad formatted N-triples");}
}
}

How to catch all exceptions that aren't already thrown by function?

I am a little doubtful this is possible, but getting more information about this would be very helpful. I am wondering how to catch all exceptions that a function doesn't already throw.
Say I have a function:
public int func(int a, int b) throws IOException, EOFException {
try {
doSomething(a, b);
} catch (AllExceptionsExceptionIOandEOF e) {
doSomethingWithError(e);
}
return 0;
}
Is there a way to tell Java how to do that? I know throwing the generic Exception works for all, but I want to throw all but the thrown exception.
If this is considered bad practice, why? And what is a good alternative to accomplish the same goal?
(PS -- I know, I know the adage that all possible exceptions need to be handled individually. For my purposes, I just want to catch the errors, log them in a database, and see what things are coming up that we missed during development. I am reluctant to catch the generic Exception when my function is already throwing 2 exceptions)
It just occured to me, one way would be to say:
try {
doSomething(a, b);
} catch (AllExceptionsExceptionIOandEOF e) {
doSomethingWithError(e);
if (e instanceof IOException)
throw e;
if (e instanceof EOFException)
throw e;
}
Is there a more elegant way of doing this though?
EDIT - The project is done in Java 6 compliance, unfortunately. I know Java 7 has made Try/Catches a bit more flexible though.
try {
doSomething(a, b);
} catch (IOException e) {
throw e;
} catch (EOFException e) {
throw e;
} catch (Exception e){
doSomethingWithError(e);
}
In pre java1.7
try{}
catch(FileNotFoundException e){}
catch(IOException e){}
catch(Exception e){
//anything not handled in other catch clause
}
Just be sure to declare your catch clauses from more specific to less specific.
In java 1.7 you can do fancier things:
catch(IOException | EOFException e){}
Since EOFException extends IOException you can catch IOException and throw it as below
catch( IOException e){
//do what you want
}
From java 1.7 you can group exceptions behaviour.
try{
//some code
}catch( IOException | AnotherException e){
//do what you want
}catch(RuntimeException re){
//happen a runtimexception
}
And to catch all exceptions that function doesn't throw it only can be RuntimeException and subclasses cause they are unchecked exceptions.
And for hierachy exceptions, first the subclasses and then more general.
For example :
catch(EOFException e){
}catch(IOException e){
}
By the way, only catch exception once.
Per the other answers, especially pre-Java 1.7, you don't have a really good answer. If this is going to be done in many places in your code, and you primarily want it for development, I might suggest creating a special handler:
class ExceptionHandler
{
public static void handle(Throwable t, Class<? extends Exception> rethrowClasses...)
{
for (Class e : rethrowClasses)
{
if e.isInstance(t)
{
throw t;
}
}
}
}
Then in your exception block:
try
{ ... }
catch (Exception e)
{
ExceptionHandler.handle(e, IOException.class, EOFException.class);
// other processing
}
That would re-throw the requested exceptions, and you have a vararg list of which exceptions to re-throw for each exception block. You can re-use that and only add one line to each exception block. You could adjust the logic as needed to log the non-handled exceptions, or whatever else is needed.
It's not great, but there just aren't a lot of good solutions to your problem.

Is it possible in Java to catch two exceptions in the same catch block? [duplicate]

This question already has answers here:
Can I catch multiple Java exceptions in the same catch clause?
(10 answers)
Closed 8 years ago.
I need to catch two exceptions because they require the same handling logic. I would like to do something like:
catch (Exception e, ExtendsRuntimeException re) {
// common logic to handle both exceptions
}
Is it possible to avoid duplicating the handler code in each catch block?
Java 7 and later
Multiple-exception catches are supported, starting in Java 7.
The syntax is:
try {
// stuff
} catch (Exception1 | Exception2 ex) {
// Handle both exceptions
}
The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.
Java 6 and earlier
Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.
Approach #1
try {
// stuff
} catch (Exception1 ex) {
handleException(ex);
} catch (Exception2 ex) {
handleException(ex);
}
public void handleException(SuperException ex) {
// handle exception here
}
This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.
Approach #2
try {
// stuff
} catch (SuperException ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
// handle exception
} else {
throw ex;
}
}
Once again, we have a potential problem with signatures.
Approach #3
try {
// stuff
} catch (SuperException ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
// handle exception
}
}
If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!
Java <= 6.x just allows you to catch one exception for each catch block:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Documentation:
Each catch block is an exception handler and handles the type of
exception indicated by its argument. The argument type, ExceptionType,
declares the type of exception that the handler can handle and must be
the name of a class that inherits from the Throwable class.
For Java 7 you can have multiple Exception caught on one catch block:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
Documentation:
In Java SE 7 and later, a single catch block can handle more than one
type of exception. This feature can reduce code duplication and lessen
the temptation to catch an overly broad exception.
Reference:
http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
If you aren't on java 7, you can extract your exception handling to a method - that way you can at least minimize duplication
try {
// try something
}
catch(ExtendsRuntimeException e) { handleError(e); }
catch(Exception e) { handleError(e); }
For Java < 7 you can use if-else along with Exception:
try {
// common logic to handle both exceptions
} catch (Exception ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
}
else {
throw ex;
// or if you don't want to have to declare Exception use
// throw new RuntimeException(ex);
}
}
Edited and replaced Throwable with Exception.
http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.
try {
// your code
} catch (Exception1 | Exception2 ex) {
// Handle 2 exceptions in Java 7
}
I'm making study cards, and this thread was helpful, just wanted to put in my two cents.
Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block.
A very basic Example:
try {
// some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}
But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.
try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
throw e;
}
So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code.
I found this article which explains this feature very well along with its implementation.
Improved and Better Exception Handling from Java 7
This may help you too.

Beanshell catch(ex): Exception or Throwable?

What type of exception is caught by the beanshell catch(ex): Exception or Throwable?.
Example:
try {
.... } catch (ex) { }
That loosely typed catch will catch everything "Throwable." That will include Errors, Exceptions and their myriad children. You can easily confirm this with:
try {
new Throwable("Something Exceptional");
} catch (ex) {
System.err.println(ex.getMessage());
}
Throwable is a superclass (essentially) of Exception--anything that Exception catches will also be caught by Throwable. In general usage they are the same, you rarely (if ever) see other throwable types.

Categories

Resources