2012-09-20 31 views
1

我正在開發一個J2ME應用程序,我想爲異常處理一個很好的做法,我要把一些例外像異常處理在J2ME

ConnectionNotFoundException, IOException, XmlPullParserException, OutOfMemory, Exception 

我不想捕獲所有這些異常在我做

每種方法,所以我認爲我可以做一個新的類

這個類將處理所有其他

我做這個類

public class ExceptionHandler extends Exception { 

    private Exception thrownException; 

    public ExceptionHandler(Exception thrownExc) { 
     this.thrownException = thrownExc; 

     if (thrownException.getClass().isInstance(ConnectionNotFoundException.class)) { 
      // DO SOMETHING 
     } else if (thrownException.getClass().isInstance(IOException.class)) { 
      // DO SOMETHING 
     } else if (thrownException.getClass().isInstance(XmlPullParserException.class)) { 
      // DO SOMETHING 
     } else if (thrownException.getClass().isInstance(NullPointerException.class)) { 
      // DO SOMETHING 
     } else if (thrownException.getClass().isInstance(OutOfMemoryError.class)) { 
      // DO SOMETHING 
     } else if (thrownException.getClass().isInstance(Exception.class)) { 
      // DO SOMETHING 
     } 
    } 
} 

,但我不知道這是否是一個好辦法與否,也是我有錯誤,當我與我的更換引發的異常

所以我能做些什麼嗎?

回答

2

您處在正確的軌道上,這是處理錯誤的最佳方式。您也可以在自定義異常類中傳遞稱爲消息的第二個參數,然後在其中顯示消息。事情是這樣的:

if (thrownException.getClass().isInstance(ConnectionNotFoundException.class)) { Dialog.alert(msg);
}

而且從調用類,你只需要調用new ExceptionHandler(exception, Constants.msg)

的Constants.java類將持有的所有錯誤消息。