Evil Behavior with Unchecked Checked Exceptions
Anders Nordås shows how to throw a checked exception without declaring a throws clause. The method uses some inherently evil mechanisms (the name of the class “sun.misc.Unsafe” should be a tip of), and like Anders says, this should probably never be used in production.
Basically, calling sun.misc.Unsafe.throwException will throw a checked exception without alerting the compiler. The exception is not wrapped, but it cannot be caught by its class name, as it is not declared. Here is some code to illustrate:
public class PureEvilness { public static void throwIt(IOException exception) { // See Anders' blog for implementation // Notice: No "throws" clause! } public static void main(String[] args) { /* * Error: "Unreachable catch block for IOException. * This exception is never thrown from the try statement block" try { throwIt(new IOException()); } catch (IOException e) { // Deal } */ try { throwIt(new IOException()); } catch (Exception e) { if (e.getClass() == IOException.class) { System.err.println("It was an IOException!"); } // Deal } } }
The wonders of checked exceptions never cease.
This work is licensed under a
Creative Commons Attribution 3.0 License.
Print This Post