Java SneakyThrow of exceptions, type erasure

前端 未结 4 959
误落风尘
误落风尘 2020-11-27 19:44

Can someone explain this code?

public class SneakyThrow {


  public static void sneakyThrow(Throwable ex) {
    SneakyThrow.sneakyTh         


        
4条回答
  •  离开以前
    2020-11-27 19:59

    he above code seems to mean that finally we can also assign a value of type Cat to a variable of type Dog or something like that.

    You have to think in terms of how the classes are structured. T extends Throwable and you are passing Exception to it. This is like assigning Dog to Animal not Dog to Cat.

    The compiler has rules about which Throwable are checked and which are not, based on inheritance. These are applied at compile time and it is possible to confuse the compiler into allowing you to throw a check exception. At runtime this has no impact.


    Checked exceptions are a compile time feature (like generics)

    BTW Throwable is a checked exception as well. If you sub class it, it will be checked unless it is a sub-class of Error or RuntimeException.

    Two other way to throw checked exceptions without the compiler being aware that you are doing this.

    Thread.currentThread().stop(throwable);
    
    Unsafe.getUnsafe().throwException(throwable);
    

    The only difference is that both use native code.

提交回复
热议问题