从构造函数抛出异常?

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);

    }

}


慕斯709654
浏览 70回答 1
1回答

猛跑小猪

您的 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 ,而在您的代码中则不会。没有看到这一切就无法判断。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java