gpt4 book ai didi

java - 从构造函数抛出异常?

转载 作者:行者123 更新时间:2023-12-01 23:08:43 24 4
gpt4 key购买 nike

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 block 。这个异常永远不会从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);
}
}

最佳答案

您的 catch block 无法访问,因为 try block 中没有任何内容抛出 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() 会抛出一个 ValidationException ,而在您的代码中却没有。没有看到全部就无法判断。

关于java - 从构造函数抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58385230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com