亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

覆蓋 Java 中的異常

覆蓋 Java 中的異常

烙印99 2023-02-23 10:15:17
public class Student {    checkAge (Student student) {        try {            if (student.getAge() > 18 ) {                throw new CustomException("Student is older than 18 years.");            }        } catch (CustomException e) {            handleException(e);        }    } public class HandleException {    public static sendToErrorReport (CustomException customException) {        //trying to do something like this, but the below code throws an error.        customException.setMessage(customException.getMessage() +" ; Student -> " + customException.getStudent().getStudentName);    }}我已經創建了一個自定義類來處理我的項目中發生的異常。我的要求是更改異常消息并將一些數據附加到異常消息并將其傳遞給我的自定義類。所以基本上我需要在設置異常消息后對其進行編輯。有什么辦法可以做到這一點?
查看完整描述

3 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

這是擴展 RuntimeException 類的完整 CustomException 類。您可以定義代碼和消息。


public class CustomException extends RuntimeException {


    private String code;

    private String message;


    public CustomException() {

        super();

    }


    public CustomException(Exception e) {

        super(e);

    }


    public CustomException(String code, String message, Exception e) {

        super(message, e);

        this.code = code;

    }

}


查看完整回答
反對 回復 2023-02-23
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

你可以覆蓋類getMessage的方法Exception


class CustomException extends java.lang.Exception{


    @Override

    public String getMessage(){

        return super.getMessage() + "- My Message";

    }


}


查看完整回答
反對 回復 2023-02-23
?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

在您的代碼中拋出異常時


try{

//Some code here

}catch(Exception e){

 throw new CustomeException("Your text here")

}

當您在其他地方捕獲 CustomeException 時,您可以對其進行修改。


try{

//Some code here

}catch(CustomException e){

String message = e.getMessage();

//Do stuff with previous message

 throw new Custom2Exception("Your next text here")

}


查看完整回答
反對 回復 2023-02-23
  • 3 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號