How do JUnit masks check exceptions?

JUnit 5 masks noted exceptions with this code:

public static RuntimeException throwAsUncheckedException(Throwable t) {
    Preconditions.notNull(t, "Throwable must not be null");
    ExceptionUtils.throwAs(t);

    // Appeasing the compiler: the following line will never be executed.
    return null;
}

@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwAs(Throwable t) throws T {
    throw (T) t;
}

In a throwAs call, how does Java decide on a variable of type T?

More importantly, how does this code mask the thrown exception?

+4
source share
1 answer

I believe that Tcounts RuntimeException. I assume that from making the following change to the code throwAsUncheckedException:

var o = ExceptionUtils.throwAs(t);

... and changing the announcement throwAsto:

private static <T extends Throwable> T throwAs(Throwable t) throws T

(Note that I use varfrom Java 10 so that the compiler infers the type without additional information.)

After compiling and then using, javap -cyou can see what's there checkcastto RuntimeException:

invokestatic  #2  // Method throwAs:(Ljava/lang/Throwable;)Ljava/lang/Throwable;
checkcast     #3  // class java/lang/RuntimeException
astore_1

throwAs , - - , , T, RuntimeException .

JLS 18, :

, αi, αi RuntimeException, Ti = RuntimeException.

Throwable. , , 18 , ", ", .

, throwAsUncheckedException ( ) :

ExceptionUtils.<RuntimeException>throwAs(t);

, . , RuntimeException. , , - , . T ... RuntimeException, . : , , .

JVM , , , , JVM. .

+1
source

Source: https://habr.com/ru/post/1695978/


All Articles