Skip to content

利用泛型的类型擦除,在方法不声明 throws 异常时,抛出 checked 异常 #226

Open
@Bpazy

Description

@Bpazy

参考 org.apache.commons.lang3.exception.ExceptionUtils 的做法:

    public static <R> R rethrow(Throwable throwable) {
        // claim that the typeErasure invocation throws a RuntimeException
        return ExceptionUtils.<R, RuntimeException> typeErasure(throwable);
    }

    @SuppressWarnings("unchecked")
    private static <R, T extends Throwable> R typeErasure(Throwable throwable) throws T {
        throw (T) throwable;
    }

测试:

public class Main {
    public static void main(String[] args) {
        try {
            throw new Exception();
        } catch (Exception e) {
            ExceptionUtils.rethrow(e);
        }
    }
}

输出:

Exception in thread "main" java.lang.Exception
	at com.github.bpazy.test.Main.main(Main.java:14)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions