[英]java exception catching in a different class than throwing
我一直在做的代碼可以做兩件事:
有一個執行計算的類(邏輯)
有一個顯示結果的類。
我想知道是否有可能在Display類中使用try / catch語句,在那里我將嘗試捕獲源自邏輯類的異常。
Display會執行類似於logic.execute(input);的行;
我能夠創建一個自定義異常類,其中將以下內容放置在顯示類中:
try{
logic.execute(input);
}catch(CustomException e){
//print statements
}
但是,我希望能夠完全打印發生的錯誤,例如NullPointerException。
當我說打印時,我的意思是控制台中的輸出。 (但它必須來自顯示類)
如果有這種怪事,請告訴我。
感謝大伙們!
是的,有可能。
您將需要自定義異常類來擴展RuntimeException
而不是Exception
,否則編譯器將抱怨您未捕獲所引發的異常。
看到這篇文章: 用Java拋出自定義異常
簡單的工作示例:
public class ExceptionTest
{
public static void main(String[] args)
{
SomeClass myObject = new SomeClass();
myObject.testFunction();
}
}
public class SomeClass
{
private SomeOtherClass someOther = new SomeOtherClass();
public void testFunction()
{
try{
someOther.someOtherFunction();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
public class SomeOtherClass
{
public void someOtherFunction()
{
throw new CustomException("This is a custom exception!");
}
}
public class CustomException extends RuntimeException
{
public CustomException(String message)
{
super(message);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.