简体   繁体   中英

Throw an exception from a constructor?

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

Hello, this is my code and i need to throw a SectionException if this constructor fails but its not letting me to do because of "Unreachable catch block for ValidationException. This exception is never thrown from the try statement body " How do i fix it? Here is similar code that works fine

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

Your catch block is unreachable because nothing in the try block throws a ValidationException . Either manually throw this exception, such as for example:

if (isValidSectionNumber(sectionNumber))
    this.sectionNumber = sectionNumber;
else
    throw new ValidationException("Validation error: section number invalid");

Or make your catch accept a generic error, ex

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

Alternatively, you could throw it from one of the methods you're using in your if conditions too.

I would guess in the working code you supplied, one or more of isValidStudentId() , isValidFirstName() , isValidLastName() throws a ValidationException where as in your code it does not. Can't tell without seeing it all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM