In C#, I can use the throw; statement to rethrow an exception while preserving the stack trace:
try { ... } catch (Exception e) { if (e is FooException) throw; } Is there something like this in Java (that doesn't lose the original stack trace)?
catch (WhateverException e) { throw e; } will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.
catch(Exception e) { throw e; } that will be unhandled. If you catch(InterruptedException ie) { throw ie; } it will be handled. As a rule of thumb, don't catch(Exception e) - this isn't pokemon, and we don't want to catch 'em all!You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:
try { ... } catch (Exception e) { throw new YourOwnException(e); } throw new YourOwnException("Error while trying to ....", e);YourOwnException is properly set up, see the 4 public constructors on RuntimeException which call super.I would prefer:
try { ... } catch (FooException fe){ throw fe; } catch (Exception e) { // Note: don't catch all exceptions like this unless you know what you // are doing. ... } Exception is typically not the right thing to do, in most (but not all) cases.In Java is almost the same:
try { ... } catch (Exception e) { if (e instanceof FooException) throw e; } e after the if. Otherwise, it's just not quite right to use instanceof. You could add an ellipsis or comment stating that.public int read(byte[] a) throws IOException { try { return in.read(a); } catch (final Throwable t) { /* can do something here, like in=null; */ throw t; } } This is a concrete example where the method throws an IOException. The final means t can only hold an exception thrown from the try block. Additional reading material can be found here and here.
I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:
try { ... } catch (NoSuchMethodException | SecurityException | IllegalAccessException e) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString()); } Worked for me....:)
e. Better pack the original exception with throw new RuntimeException("Some usefull info", e). In the string, gives somes usefull info that are missing in e, for example some important arguments of your method, info about the context, or whatever will help debugging.
Throwables don't get modified by throwing them. To update the stack trace you have to callfillInStackTrace(). Conveniently this method gets called in the constructor of aThrowable.throw e;will lose the stacktrace. But not in Java.