[英]How to change the return message of Exception.getMessage()?
我需要更改方法getMessage()的返回消息,
例如,我有一個ArithmeticException ,當我寫:
try{c=a/0;}
catch(ArithmeticException excep){System.out.println( excep.getMessage() );}
我執行的代碼是: /零 。
因此,我想通過覆蓋getMesage方法來更改此結果。
我創建了一個名為MyException的新類,該類繼承自ArithmeticExceprtion並覆蓋了方法getMessage ,然后,我將上一個代碼中的異常類型從ArithmeticException更改為新名稱類MyException :
public class MyException extends ArithmeticException{
@override
public String getMessage(){
retun "new code message";}
}
並且我更改了第一個代碼,我寫錯了:
try{c=a/0;}
catch(MyException excep){System.out.println( excep.getMessage() );}
當我執行了這段代碼后,我收到了相同的錯誤消息,好像我沒有捕獲到異常一樣:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at main.test.main(Test.java:33)
因此,我的問題是:如何更改方法getMessage()的消息?
c=a/0
總是拋出ArithmeticException
因為它是通過這種方式實現的。
如果您編寫的是自己的除法函數,當除以0時會拋出MyException
,那么您實際上可以捕獲它:
float division(float a, float b) {
if(b == 0)
throw new MyException();
return a/b;
}
...
try {
c = division(a, b);
} catch(MyException e) {
System.out.println(e.getMessage());
}
如果使用自己定義的異常,則必須手動將其拋出
throw new MyException();
否則,它將拋出類ArithmeticException的實例,因此將觸發其自己的getMessage()函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.