Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?
Thoughts that came to mind are using for example interceptors or aspect-oriented programming.
I haven't tried this, so I don't know if the JVM would restrict something like this, but maybe you could compile code which throws ChuckNorrisException, but at runtime provide a class definition of ChuckNorrisException which does not extend Throwable.
UPDATE:
It doesn't work. It generates a verifier error:
Exception in thread "main" java.lang.VerifyError: (class: TestThrow, method: ma\
in signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestThrow. Program will exit.
UPDATE 2:
Actually, you can get this to work if you disable the byte code verifier! (-Xverify:none)
UPDATE 3:
For those following from home, here is the full script:
Create the following classes:
public class ChuckNorrisException
extends RuntimeException // <- Comment out this line on second compilation
{
public ChuckNorrisException() { }
}
public class TestVillain {
public static void main(String[] args) {
try {
throw new ChuckNorrisException();
}
catch(Throwable t) {
System.out.println("Gotcha!");
}
finally {
System.out.println("The end.");
}
}
}
Compile classes:
javac -cp . TestVillain.java ChuckNorrisException.java
Run:
java -cp . TestVillain
Gotcha!
The end.
Comment out "extends RuntimeException" and recompile ChuckNorrisException.java only :
javac -cp . ChuckNorrisException.java
Run:
java -cp . TestVillain
Exception in thread "main" java.lang.VerifyError: (class: TestVillain, method: main signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestVillain. Program will exit.
Run without verification:
java -Xverify:none -cp . TestVillain
The end.
Exception in thread "main"
After having pondered this, I have successfully created an uncatchable exception. I chose to name it JulesWinnfield, however, rather than Chuck, because it is one mushroom-cloud-laying-mother-exception. Furthermore, it might not be exactly what you had in mind, but it certainly can't be caught. Observe:
public static class JulesWinnfield extends Exception
{
JulesWinnfield()
{
System.err.println("Say 'What' again! I dare you! I double dare you!");
System.exit(25-17); // And you shall know I am the LORD
}
}
public static void main(String[] args)
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
System.out.println("There's a word for that Jules - a bum");
}
}
Et voila! Uncaught exception.
Output:
run:
Say 'What' again! I dare you! I double dare you!
Java Result: 8
BUILD SUCCESSFUL (total time: 0 seconds)
When I have a little more time, I'll see if I can't come up with something else, as well.
Also, check this out:
public static class JulesWinnfield extends Exception
{
JulesWinnfield() throws JulesWinnfield, VincentVega
{
throw new VincentVega();
}
}
public static class VincentVega extends Exception
{
VincentVega() throws JulesWinnfield, VincentVega
{
throw new JulesWinnfield();
}
}
public static void main(String[] args) throws VincentVega
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
}
catch(VincentVega vv)
{
}
}
Causes a stack overflow - again, exceptions remain uncaught.
With such an exception it would obviously be mandatory to use a System.exit(Integer.MIN_VALUE); from the constructor because this is what would happen if you threw such an exception ;)
Any code can catch Throwable. So no, whatever exception you create is going to be a subclass of Throwable and will be subject to being caught.
public class ChuckNorrisException extends Exception {
public ChuckNorrisException() {
System.exit(1);
}
}
(Granted, technically this exception is never actually thrown, but a proper ChuckNorrisException can't be thrown -- it throws you first.)
Any exception you throw has to extend Throwable, so it can be always caught. So answer is no.
If you want to make it difficult to handle, you can override methods getCause(), getMessage(), getStackTrace(), toString() to throw another java.lang.ChuckNorrisException.
My answer is based on #jtahlborn's idea, but it's a fully working Java program, that can be packaged into a JAR file and even deployed to your favorite application server as a part of a web application.
First of all, let's define ChuckNorrisException class so that it doesn't crash JVM from the beginning (Chuck really loves crashing JVMs BTW :)
package chuck;
import java.io.PrintStream;
import java.io.PrintWriter;
public class ChuckNorrisException extends Exception {
public ChuckNorrisException() {
}
#Override
public Throwable getCause() {
return null;
}
#Override
public String getMessage() {
return toString();
}
#Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
}
#Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
}
}
Now goes Expendables class to construct it:
package chuck;
import javassist.*;
public class Expendables {
private static Class clz;
public static ChuckNorrisException getChuck() {
try {
if (clz == null) {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("chuck.ChuckNorrisException");
cc.setSuperclass(pool.get("java.lang.Object"));
clz = cc.toClass();
}
return (ChuckNorrisException)clz.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
And finally the Main class to kick some butt:
package chuck;
public class Main {
public void roundhouseKick() throws Exception {
throw Expendables.getChuck();
}
public void foo() {
try {
roundhouseKick();
} catch (Throwable ex) {
System.out.println("Caught " + ex.toString());
}
}
public static void main(String[] args) {
try {
System.out.println("before");
new Main().foo();
System.out.println("after");
} finally {
System.out.println("finally");
}
}
}
Compile and run it with following command:
java -Xverify:none -cp .:<path_to_javassist-3.9.0.GA.jar> chuck.Main
You will get following output:
before
finally
No surprise - it's a roundhouse kick after all :)
In the constructor you could start a thread which repeatedly calls originalThread.stop (ChuckNorisException.this)
The thread could catch the exception repeatedly but would keep throwing it until it dies.
No. All exceptions in Java must subclass java.lang.Throwable, and although it may not be good practice, you can catch every type of exception like so:
try {
//Stuff
} catch ( Throwable T ){
//Doesn't matter what it was, I caught it.
}
See the java.lang.Throwable documentation for more information.
If you're trying to avoid checked exceptions (ones that must be explicitly handled) then you will want to subclass Error, or RuntimeException.
Actually the accepted answer is not so nice because Java needs to be run without verification, i.e. the code would not work under normal circumstances.
AspectJ to the rescue for the real solution!
Exception class:
package de.scrum_master.app;
public class ChuckNorrisException extends RuntimeException {
public ChuckNorrisException(String message) {
super(message);
}
}
Aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.ChuckNorrisException;
public aspect ChuckNorrisAspect {
before(ChuckNorrisException chuck) : handler(*) && args(chuck) {
System.out.println("Somebody is trying to catch Chuck Norris - LOL!");
throw chuck;
}
}
Sample application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
catchAllMethod();
}
private static void catchAllMethod() {
try {
exceptionThrowingMethod();
}
catch (Throwable t) {
System.out.println("Gotcha, " + t.getClass().getSimpleName() + "!");
}
}
private static void exceptionThrowingMethod() {
throw new ChuckNorrisException("Catch me if you can!");
}
}
Output:
Somebody is trying to catch Chuck Norris - LOL!
Exception in thread "main" de.scrum_master.app.ChuckNorrisException: Catch me if you can!
at de.scrum_master.app.Application.exceptionThrowingMethod(Application.java:18)
at de.scrum_master.app.Application.catchAllMethod(Application.java:10)
at de.scrum_master.app.Application.main(Application.java:5)
A variant on the theme is the surprising fact that you can throw undeclared checked exceptions from Java code. Since it is not declared in the methods signature, the compiler won't let you catch the exception itself, though you can catch it as java.lang.Exception.
Here's a helper class that lets you throw anything, declared or not:
public class SneakyThrow {
public static RuntimeException sneak(Throwable t) {
throw SneakyThrow.<RuntimeException> throwGivenThrowable(t);
}
private static <T extends Throwable> RuntimeException throwGivenThrowable(Throwable t) throws T {
throw (T) t;
}
}
Now throw SneakyThrow.sneak(new ChuckNorrisException()); does throw a ChuckNorrisException, but the compiler complains in
try {
throw SneakyThrow.sneak(new ChuckNorrisException());
} catch (ChuckNorrisException e) {
}
about catching an exception that is not thrown if ChuckNorrisException is a checked exception.
The only ChuckNorrisExceptions in Java should be OutOfMemoryError and StackOverflowError.
You can actually "catch" them in the means that a catch(OutOfMemoryError ex) will execute in case the exception is thrown, but that block will automatically rethrow the exception to the caller.
I don't think that public class ChuckNorrisError extends Error does the trick but you could give it a try. I found no documentation about extending Error
Is it possible to construct a snippet of code in java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?
Yes, and here's the answer: Design your java.lang.ChuckNorrisException such that it is not an instance of java.lang.Throwable. Why? An unthrowable object is uncatchable by definition because you can never catch something that can never be thrown.
You can keep ChuckNorris internal or private and encapsulate him or swollow him...
try { doChuckAction(); } catch(ChuckNorrisException cne) { /*do something else*/ }
Two fundamental problems with exception handling in Java are that it uses the type of an exception to indicate whether action should be taken based upon it, and that anything which takes action based upon an exception (i.e. "catch"es it) is presumed to resolve the underlying condition. It would be useful to have a means by which an exception object could decide which handlers should execute, and whether the handlers that have executed so far have cleaned things up enough for the present method to satisfy its exit conditions. While this could be used to make "uncatchable" exceptions, two bigger uses would be to (1) make exceptions which will only be considered handled when they're caught by code that actually knows how to deal with them, and (2) allow for sensible handling of exceptions which occur in a finally block (if a FooException during a finally block during the unwinding of a BarException, both exceptions should propagate up the call stack; both should be catchable, but unwinding should continue until both have been caught). Unfortunately, I don't think there would be any way to make existing exception-handling code work that way without breaking things.
It is easily possible to simulate a uncaught exception on the current thread. This will trigger the regular behavior of an uncaught exception, and thus gets the job done semantically. It will, however, not necessarily stop the current thread's execution, as no exception is actually thrown.
Throwable exception = /* ... */;
Thread currentThread = Thread.currentThread();
Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
currentThread.getUncaughtExceptionHandler();
uncaughtExceptionHandler.uncaughtException(currentThread, exception);
// May be reachable, depending on the uncaught exception handler.
This is actually useful in (very rare) situations, for example when proper Error handling is required, but the method is invoked from a framework catching (and discarding) any Throwable.
Call System.exit(1) in the finalize, and just throw a copy of the exception from all the other methods, so that the program will exit.
Related
Consider the following java code:
public void write(FrameConsumer fc) throws FFmpegFrameRecorder.Exception{
frameStream.forEach(n -> fc.consume(n));
}
In this case "frameStream" is a Stream of Objects that can be passed to the "consume" method, and fc is a class containing the "consume" method. Another important note is that the "consume" method throws a "FFmpegFrameRecorder.Exception", which I would like to pass on to whatever method calls "write" in the future.
However the above code does not compile, because: "Unhandled exception type FFmpegFrameRecorder.Exception Java(16777384)". Why is that?
Best regards,
CCI
EDIT:
Puting a try_catch block inside the lambda expression does not solve the problem either, hence:
public void write(FrameConsumer fc) throws FFmpegFrameRecorder.Exception{
frameStream.forEach(n -> {
try {
fc.consume(n);
} catch (FFmpegFrameRecorder.Exception e) {
throw e; //**this part does not compile**
}
});
}
(As provided by #Soumya Manna) does not compile either. The compiler still wants for the program to handle the "FFmpegFrameRecorder.Exception e" as it is thrown.
You cannot do this in lambda. You may simple write for loop and throw it or use try-catch block in lambda and throw Runtime exception there.
You could wrap the exception in a RuntimeException and then unwrap it:
public class ExceptionWrapper extends RuntimeException {
public ExceptionWrapper(Throwable cause) {
super(cause);
}
}
// ...
public void write(FrameConsumer fc) throws FFmpegFrameRecorder.Exception {
try {
frameStream.forEach(n -> {
try {
fc.consume(n));
} catch(FFmpegFrameRecorder.Exception e) {
throw new ExceptionWrapper(e);
}
});
} catch(ExceptionWrapper e) {
throw (FFmpegFrameRecorder.Exception) e.getCause();
}
}
The reason the lambda can't throw a checked exception is that java.lang.Stream#forEach's parameter (action) is of type java.util.function.Consumer, whose only non-default method, accept, does not declare any exceptions.
See also: https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
#Override
Public class example {
void test {
try {
someMethod(); //This throws TimeoutException
} catch (TimeoutException ex) {
throw new TimeoutException(ex); //It doesn't throw error if I replace this with throw new RuntimeException(ex)
} }
}
The above example gives an error as 'throw new TimeoutException(ex)' as "TimeoutException(java.lang.string) in java.util.concurrent.TimeoutException cannot be applied to (java.util.concurrent.TimeoutException)".
But it doesn't throw an error if I replace it with 'throw new RuntimeException(ex)';
TimeoutException doesn't have a constructor that accepts a TimeoutException as an argument of the form TimeoutException(TimeoutException cause) or similar.
You can instead:
TimeoutException localtoe=new TimeoutException("test failed");
localtoe.initCause(ex);
throw localtoe;
Or equally:
throw new TimeoutException("test failed").initCause(ex);
initCause() may only be called once and only if cause wasn't set by a constructor. It's a funny little method that acts like a constructor after-thought(*).
There's nothing necessarily wrong with wrapping an exception as the cause of an exception.
Suppose testFunction() connects and then performs some operation.
You might want to throw an exception with message "connection failed in testFunction" and another "operation failed in testFunction" depending on what sub-step failed.
But if you don't need to provide so much detail you can just throw ex or let the method unwind without itself catching anything.
Here's a little example:
import java.util.concurrent.TimeoutException;
class Example{
private static void connect() throws TimeoutException {
//Dummy connection that just fails...
throw new TimeoutException("connection failed");
}
private static void process() throws TimeoutException {
try {
connect();
}catch(TimeoutException toe){
TimeoutException toeout=new TimeoutException("process failed because connection failed.");
toeout.initCause(toe);
throw toeout;
}
//Code for when connection succeeds...
}
public static void main (String[] args) throws java.lang.Exception
{
try{
process();
}catch(TimeoutException toe){
System.out.println(toe);
}
}
}
Expected output:
java.util.concurrent.TimeoutException: process failed because connection failed.
(*) initCause() looks like an after-thought and is somewhat. It was added to Java 1.4 in 2002. The documentation talks about 'legacy' constructors. Rather than double up the number of constuctors (to add one with a Throwable cause argument) it appears it was decided to allow this as bolt-on initialization.
It's debatable whether that was the best solution.
Things I observed in your question
you are trying to call a method directly from class in a try cache block. which is wrong you have to create method and call it from that
you want to throw an exception. SO you have to throw it method level from where you are calling it
please find the demo solution below :
public class example {
public void testFunction() throws TimeoutException {
try {
someFunction();
} catch (TimeoutException ex) {
throw ex;
}
}
public void someFunction() throws TimeoutException {
}
}
Java has 2 categories of exceptions: checked and unchecked. Checked exception (usually subclasses of Exception) must be declared in function signatures, while unchecked ones (usually subclasses of RuntimeException) must not.
TimeoutException is a checked exception. When it could be thrown from a method that does not declare it, you have 2 options:
declare it in the signature:
public void func1() throws TimeoutException {
somefunction();
}
clean and simple but it can be problemetic is func1 is an override of a function not declared to throw this exception, of it it is called from another function (suppose from a framework) that does not declare it either
hide it in an unchecked exception
public void func1() {
try {
somefunction();
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
you lose the declarative part (checked exceptions exist for that reason), but at least it allows you to call it from function not declaring it.
You have roughly three options here:
Rethrow the same exception: `throw ex;'
Throw a new TimeoutException and lose the stack trace: throw new TimeoutException(ex.getMessage());
Throw an exception of another type, such as RuntimeException.
Each of these options have advantages and drawbacks, you decide.
UPDATE (thanks to #Mark Rottenveel)
Point 2 could be rewritten: throw new TimeoutException(ex.getMessage()).initCause(ex); to keep the link to the original exception.
In program of interest, during execution of a method() some HTTP related exceptions can occur. Due to something, that method was set to be able to throw ExpException. My interest is only in specific type of exception, i.e. UnknownHostException, which can be accessed by using
if (e.getCause().getCause().getCause() instanceof UnknownHostException)
which I hope you agree is very nasty way. Thus, this works fine:
public class ExportException extends Exception;
class sth{
method() throws ExpException;
}
class main{
try{
method()
} catch(ExpExceptione e){
if (e.getCause().getCause().getCause() instanceof UnknownHostException){
doSthElse();
}
}
However, I was hoping to do as described below. Unfortunately, Eclipse yells
Unreachable catch block for UnknownHostException. This exception is
never thrown from the try statement.
Is there any help for me? I don't want to use getCause()^3.
An addition: this is a big big project and I'm the new newbie and would rather not mess with outside classes, but just the "main".
My program is something like:
public class ExportException extends Exception;
class sth{
method() throws ExpException;
}
class main{
try{
method()
} catch(UnknownHostException e){
doSth();
} catch(ExpExceptione){
doSthElse();
}
UnknownHostException is a subtype of IOException which is checked exception.
Method that throws checked exceptions must declare them in throws declaration.
Consequently, when you call a method that does not have throws UnknownHostException in declaration, you will never catch this exception - code is unreachable and compiler is correct.
Here you can see how to nicely check if exception cause contains any specific exception.
static boolean hasCause(Throwable e, Class<? extends Throwable> cl) {
return cl.isInstance(e) || e.getCause() != null && hasCause(e.getCause(), cl);
}
catch(ExpException e) {
if (hasCause(e, UnknownHostException.class)) {
doSmth();
} else {
doSmthElse();
}
}
is it possible to write a thrown exception to a file without using try catch blocks?
for example
public static void method() throws Exception, SQLException{
if(Exception is thrown){
write Exception to out.txt;
write SQLException to out.txt;
}
}
or do you have to do:
public static void method(){
try{
...
}catch(Exception ex){
write ex to file;
}catch(SQLException sqlex){
write sqlex to file;
}
}
In Java, I don't think it's possible.
However, if executed on *nix, you could just redirect all output to a file (or just error output). But that's not a generic solution.
You have to catch that exception some how. If you catch it and later on decide to write it a file is ok. Given what you have above I would suggest the second way because the if-statement has no way of actually getting the exception.
The only way to catch specific errors within a method is to use a Try/Catch block. However, it is possible to have a class catch all uncaught exceptions - ie anything that doesn't have a Try/Catch around it.
You can write a custom class to implement Java's UncaughtExceptionHandler interface.
import java.lang.Thread.UncaughtExceptionHandler;
public class CustomUncaughtExceptionHandler implements UncaughtExceptionHandler {
public void uncaughtException(Thread thread, Throwable throwable) {
/* Write to file here */
}
}
You then need to tell the Java Virtual Machine to redirect uncaught exceptions to your class.
public static void main(String[] args){
Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
}
You cant do it with straight java unless you instrument the byte code (which you can do with an agent and something like asm). You can do it with an aspect, which is easier than the byte code instrumentation approach. Take aspectj for example. An aspect might be:
public aspect ExceptionAdvice {
pointcut allMethods() : execution(* *(..)) && !within(com.test.ExceptionAdvice);
after() throwing(Exception e) : allMethods() {
//write to a file or whatever - I'm lazy and just printed the stack
e.printStackTrace ();
}
}
Once you weave this to your application classes, all exceptions thrown will pass through the join point here. I just printed the stack but you can log it to a file or do whatever you want. When the join point completes, the exception continues to be thrown so the calling code has a chance to handle it. Obviously, you need to change the pointcut definition to suit your classes but this is the general idea.
No.
public static void method() throws Exception, SQLException{
if(Exception is thrown){
write Exception to out.txt;
write SQLException to out.txt;
}
}
Where does the Exception come from?
Btw.: You never declare the most abstract exception Exception to be thrown. Some RuntimeExceptions can occur nearly everywhere (Nullpointer, OutOfMemory) so it is useless to declare them everywhere. It's just noise.
public static void method() throws Exception, SQLException{
try{
...
}catch(Exception ex){
write ex to file;
}catch(SQLException sqlex){
write sqlex to file;
}
}
But if you catch it, you usually don't throw, and therefore don't declare at all to throw Exceptions.
In the second block you already catched the exception, so no need for throws Exception, SqlException.
An exception is detected on a regular line of code, so you can't add an if to each and every one. Yes, try/catch(write) is the only way.
Unless ... you use if/else instead of exception handling
You will need to catch the exception and rethrow it.
public static void method() throws Exception, SQLException{
try{
...
}
catch(SQLException sqlex){
write sqlex to file;
throw ex;
}
catch(Exception ex){
write ex to file;
throw ex;
}
}
Is there a way to annotate a method so all exceptions thrown are converted to runtime exception automagically?
#MagicAnnotation
// no throws clause!
void foo()
{
throw new Exception("bar")'
}
Project Lombok's #SneakyThrows is probably what you are looking for. Is not really wrapping your exception (because it can be a problem in a lot of cases), it just doesn't throw an error during compilation.
#SneakyThrows
void foo() {
throw new Exception("bar")'
}
You can do this with AspectJ. You declare a joinpoint (in this case invocation of the method foo) and 'soften' the exception.
Edit To elaborate a bit on this:
Say you have the following class Bar:
public class Bar {
public void foo() throws Exception {
}
}
...and you have a test like this:
import junit.framework.TestCase;
public class BarTest extends TestCase {
public void testTestFoo() {
new Bar().foo();
}
}
Then obviously the test is not going to compile. It will give an error:
Unhandled exception type Exception BarTest.java(line 6)
Now to overcome this with AspectJ, you write a very simple aspect:
public aspect SoftenExceptionsInTestCode {
pointcut inTestCode() : execution(void *Test.test*());
declare soft : Exception : inTestCode();
}
The aspect basically says that any code from within a Test (i.e.: a method that starts with "test" in a class that ends in "Test" and returns 'void') that throws an exception should be accepted by the AspectJ compiler. If an exception occurs, it will be wrapped and thrown as a RuntimeException by the AspectJ compiler.
Indeed, if you run this test as part of an AspectJ project from within Eclipse (with AJDT installed) then the test will succeed, whereas without the aspect it won't even compile.
No way to do that, at least for now I use workaround like this (simplified):
#SuppressWarnings({"rawtypes", "unchecked"})
public class Unchecked {
public static interface UncheckedDefinitions{
InputStream openStream();
String readLine();
...
}
private static Class proxyClass = Proxy.getProxyClass(Unchecked.class.getClassLoader(), UncheckedDefinitions.class);
public static UncheckedDefinitions unchecked(final Object target){
try{
return (UncheckedDefinitions) proxyClass.getConstructor(InvocationHandler.class).newInstance(new InvocationHandler(){
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target instanceof Class){
return MethodUtils.invokeExactStaticMethod((Class) target, method.getName(), args);
}
return MethodUtils.invokeExactMethod(target, method.getName(), args);
}
});
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
And the usage looks like:
import static ....Unchecked.*;
...
Writer w = ...;
unchecked(w).write(str, off, len);
The trick is that interface is "never finished" and everytime I need unchecked method somewhere, I'll wrap that object into unchecked and let IDE generate method signature in interface.
Implementation is then generic (reflective and "slow" but usually fast enough)
There are some code post-processors and bytecode-weavers but this was not possible (not even aop or other jvm based language) for my current project, so this was "invented".
I think it is possible with bytecode re-engineering, customized compiler or perhaps aspect oriented programming1. In the contrary to Java, C# has only unchecked exceptions2.
May I ask why you want to suppress the checked exceptions?
1 according to Maarten Winkels this is possible.
2 and they are thinking about introducing checked ones, according to some Channel 9 videos.
Edit: For the question: It is possible in the sense that you can annotate your methods to flag them to be a candidate for checked exception suppression. Then you use some compile time or runtime trick to apply the actual suppression / wrapping.
However, as I don't see the environment around your case, wrapping an exception in these ways might confuse the clients of that method - they might not be prepared to deal with a RuntimeException. For example: the method throws an IOException and your clients catches it as FileNotFoundException to display an error dialog. However if you wrap your exception into a RuntimeException, the error dialog gets never shown and probably it kills the caller thread too. (IMHO).
The Checked exceptions are responsability of the method implementation.
Take very very carefully this fact. if you can do not use workaround artifacts like that.
You can do this in any case via use of the fact that Class.newInstance does not wrap an Exception thrown by the no-arg constructor in an InvocationTargetException; rather it throws it silently:
class ExUtil {
public static void throwSilent(Exception e) { //NOTICE NO THROWS CLAUSE
tl.set(e);
SilentThrower.class.newInstance(); //throws silently
}
private static ThreadLocal<Exception> tl = new ThreadLocal<Exception>();
private static class SilentThrower {
SilentThrower() throws Exception {
Exception e = tl.get();
tl.remove();
throw e;
}
}
}
Then you can use this utility anywhere:
ExUtil.throwSilent(new Exception());
//or
try {
ioMethod();
} catch (IOException e) { ExUtil.throwSilent(e); }
By the way, this is a really bad idea :-)
I use the completion / template system of Eclipse to wrap any block of code easily.
Here is my template :
try { // Wrapp exceptions
${line_selection}${cursor}
} catch (RuntimeException e) { // Forward runtime exception
throw e;
} catch (Exception e) { // Wrap into runtime exception
throw new RuntimeException(
"Exception wrapped in #${enclosing_method}",
e);
}