Search code examples
exceptionkotlinruntimeexception

How kotlin changes checked exception to runtime exception?


I already know that there is no such "checked" exception things in kotlin.

but I wonder how kotlin can "transform" checked exception to runtime exception internally.

For example, below code will throws FileNotFoundException from java.io package (not from kotlin package) when there is no such file.

var s = File("hello.txt").inputStream()

Sure, There is no need to add try-catch block explicitly, but I'm curious how this works internally.

I assume that somehow they reimplemented all java checked exceptions to kotlin friendly runtime exceptions, but My guess doesn't seem right.


Solution

  • Checked exceptions are no different than unchecked exceptions at runtime. What makes them different in Java is how the Java compiler handles them. It refuses to compile code that throws a checked exception without declaring it in the throws clause of the method. The Kotlin compiler simply doesn't have this rule, and accepts such source code.

    Note that you can actually cheat with the Java compiler and throw a checked exception without declaring it in the throws clause:

    public void haha() {
        IOException e = new IOException();
        sneakyThrow(e);
    }
    
    private <E extends Exception> void sneakyThrow(Exception e) throws E {
        throw (E) e;
    }