我有兩種方法:Java泛型與異常產生編譯時錯誤
private static <T extends Throwable> void methodWithExceptionGeneric(final T t) throws T {
throw t;
}
private static void methodWithExceptionNonGeneric(final Throwable t) throws Throwable {
throw t;
}
當我調用這些方法如下所示:
methodWithExceptionGeneric(new IllegalArgumentException());
methodWithExceptionNonGeneric(new IllegalArgumentException()); // compile time error
我得到的非泛型方法編譯時錯誤說我的主方法中有一個未處理的異常,我需要聲明一個throws語句或捕獲異常。
我的問題是:爲什麼它只是抱怨非泛型方法?在我看來,泛型方法也拋出異常,所以不應該被處理呢?
你知道關於檢查和未檢查的異常嗎?什麼樣的'IllegalArgumentException'? –
@SotiriosDelimanolis我不知道 – Ogen
@Ogen然後谷歌,檢查文檔:http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html,看到它擴展了一個'java.lang.RuntimeException' – alfasin