1. 程式人生 > >異常java.lang.reflect.InvocationTargetException

異常java.lang.reflect.InvocationTargetException

今天做spring環境搭建老炮這個異常
Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
InvocationTargetException 是一種包裝由呼叫方法或構造方法所丟擲異常的受查異常。這個異常並不是Eclipse外掛開發特有的,而是標準JDK中的,它定義在 java.lang.reflect包下。在進行Java開發的時候很少會接觸到這個異常,不過在進行Eclipse外掛開發中則不同,很多API都宣告丟擲此類異常,因此必須對此異常進行處理。

    例如,我們開發一個方法用來統一處理異常:
    private static void handleException(Exception e)
    {
        MessageDialog.openError(Activator.getDefault().getWorkbench()
                .getDisplay().getActiveShell(), "error", e.getMessage());
        e.printStackTrace();
    }

    我們發現當傳遞來的引數e為InvocationTargetException 的時候彈出的對話方塊中的訊息是空的,檢視InvocationTargetException 的原始碼得知InvocationTargetException 並沒有覆蓋getMessage方法,所以訊息當然是空的了。我們需要呼叫InvocationTargetException 的getTargetException方法得到要被包裝的異常,這個異常才是真正我們需要的異常。修改程式碼如下所示:
    private static void handleException(Exception e)
    {
        String msg = null;
        if (e instanceof InvocationTargetException)
        {
            Throwable targetEx = ((InvocationTargetException) e)
                    .getTargetException();
            if (targetEx != null)
            {
                msg = targetEx.getMessage();
            }
        } else
        {
            msg = e.getMessage();
        }
        MessageDialog.openError(Activator.getDefault().getWorkbench()
                .getDisplay().getActiveShell(), "error", msg);
        e.printStackTrace();
    }