Skip to content

Instantly share code, notes, and snippets.

@leadVisionary
Created January 24, 2013 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leadVisionary/4628040 to your computer and use it in GitHub Desktop.
Save leadVisionary/4628040 to your computer and use it in GitHub Desktop.
How I prefer to handle Java's IllegalInvocationException.java
import java.lang.reflect.InvocationTargetException;
public class AllowMeToLetYouHandleErrors {
public static void main(String[] args) {
System.out.println("Yo, can I eat an error?");
try {
eater(new RuntimeException("something I can handle"));
} catch (Throwable t) {
System.out.println("Hey, I ate " + t.getMessage());
}
try {
eater(new OutOfMemoryError("I feel like stopping."));
} catch (Throwable t) {
System.out.println("I probably shouldn't go on " + t.getMessage());
}
System.out
.println("But I don't really care. Have fun! :D");
}
static void eater(Throwable t) throws Throwable {
if(t instanceof Exception) {
throw new InvocationTargetException(t, t.getLocalizedMessage());
} else {
System.out.println(t.getMessage());
throw (Error) t;
}
}
}
import java.lang.reflect.InvocationTargetException;
public class DoNotWorryAboutErrorIWillDoIt {
public static void main(String[] args) {
System.out.println("Yo, can I eat an error?");
try {
eater(new RuntimeException("something I can handle"));
} catch (Exception e) {
System.out.println("Hey, I ate " + e.getMessage());
}
try {
eater(new OutOfMemoryError("I feel like stopping."));
} catch (Exception e) {
System.out.println("But if I don't get an exception, I won't even get here" + e.getMessage());
}
System.out
.println("But I won't even get a chance to reach here after giving an error");
}
static void eater(Throwable t) throws Exception {
if(t instanceof Exception) {
throw new InvocationTargetException(t, t.getLocalizedMessage());
} else {
System.out.println(t.getMessage());
throw (Error) t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment