为了账号安全,请及时绑定邮箱和手机立即绑定

从构造函数抛出异常?

从构造函数抛出异常?

慕斯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 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信