Created
January 24, 2013 21:38
-
-
Save leadVisionary/4628040 to your computer and use it in GitHub Desktop.
How I prefer to handle Java's IllegalInvocationException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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