Uncatchable ChuckNorrisException

前端 未结 17 2143
时光取名叫无心
时光取名叫无心 2020-12-02 03:34

Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?

Thoughts that came to m

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 03:55

    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. throwGivenThrowable(t);
      }
    
      private static  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.

提交回复
热议问题