2011-03-30 75 views
30

我有以下代碼越來越UndeclaredThrowableException中,而不是我自己的異常

public Object handlePermission(ProceedingJoinPoint joinPoint, RequirePermission permission) throws AccessException, Throwable { 
    System.out.println("Permission = " + permission.value()); 
    if (user.hasPermission(permission.value())) { 
     System.out.println("Permission granted "); 
     return joinPoint.proceed(); 
    } else { 
     System.out.println("No Permission"); 
     throw new AccessException("Current user does not have required permission"); 
    } 

} 

當我使用不具有權限的用戶,我得到java.lang.reflect.UndeclaredThrowableException而不是AccessException

回答

56

AccessException是一個檢查異常,但是它從未在其throws子句(實際上 - 從截取該方法的方面)聲明它的方法拋出。這是Java中的一個異常情況,因此您的異常被UndeclaredThrowableException打包,未選中。

爲了讓您的例外,因爲就是你既可以將它聲明的方法的throws子句中由您方面被截獲,或使用替代AccessException另一個未經檢查的異常(即RuntimeException一個子類)。

+2

+1。我只會補充說,在這些情況下'UndeclaredThrowableException'包裝原始異常; 'getCause()'將返回'AccessException'。 – 2011-03-30 18:39:55

+1

我在攔截的方法中聲明瞭AccessException。更改AccessException以擴展RuntimeException的工作。 – user373201 2011-03-30 18:40:37

+5

如果您是使用'UndeclaredThrowableException'捕獲的代碼的作者,那麼閱讀[此帖有一些詳細信息]可能會很好(http://amitstechblog.wordpress.com/2011/07/24/java -proxies-and-undeclaredthrowableexception /) – EdgeCaseBerg 2014-01-29 21:45:15