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

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

從構造函數拋出異常?

從構造函數拋出異常?

慕斯709654 2023-10-27 10:51:34
public Section(Course course, String sectionNumber)        throws SectionException{try {/* No checking needed as a course is defined by another class. */this.thisCourse = course;this.sectionNumber = DEFAULT_SECTION_NUMBER;if( isValidSectionNumber(sectionNumber) )    this.sectionNumber = sectionNumber;} catch( ValidationException ex ) {    throw new SectionException("Error in constructor", ex);}}你好,這是我的代碼,如果這個構造函數失敗,我需要拋出一個SectionException,但它不允許我這樣做,因為“無法訪問ValidationException的catch塊。這個異常永遠不會從try語句主體中拋出”我該如何修復它?這是運行良好的類似代碼public Student(String studentID, String firstName, String lastName)        throws StudentException{    /* Initialize with the provided data using the validated values. */    try    {        if( isValidStudentID(studentID) )        this.studentID = studentID;        if( isValidFirstName(firstName) )            this.firstName = firstName;        if( isValidLastName(lastName) )            this.lastName = lastName;    } catch( ValidationException ex )    {        throw new StudentException("Error in constructor", ex);    }}
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

您的 catch 塊無法訪問,因為 try 塊中沒有任何內容拋出ValidationException. 要么手動拋出此異常,例如:


if (isValidSectionNumber(sectionNumber))

    this.sectionNumber = sectionNumber;

else

    throw new ValidationException("Validation error: section number invalid");

或者讓你的捕獲接受一般錯誤,例如


catch (Exception e) { /* other code here */ }

或者,您也可以從 if 條件中使用的方法之一拋出它。


我猜想在您提供的工作代碼中,一個或多個isValidStudentId(), isValidFirstName(),isValidLastName()會拋出一個ValidationExceptionwhere ,而在您的代碼中則不會。沒有看到這一切就無法判斷。


查看完整回答
反對 回復 2023-10-27
  • 1 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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