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 ,而在您的代碼中則不會。沒有看到這一切就無法判斷。
添加回答
舉報
0/150
提交
取消