java - 如何删除 Java 代码中未处理的异常错误
问题描述
我是 Java 新手,正在尝试处理异常处理代码。一切对我来说都很好,直到我得到未处理的异常错误。谁能帮我更正代码并告诉我的错误,这样我就再也不能犯了?
异常类- 创建这个以检索不同异常的消息
// Implement user defined exception classes
class InvalidAgeException extends Exception{
public InvalidAgeException(String message) {
super(message);
}
}
class InvalidJobProfileException extends Exception{
public InvalidJobProfileException(String message) {
super(message);
}
}
class InvalidNameException extends Exception{
public InvalidNameException(String message) {
super(message);
}
}
申请人类- 设置和获取申请人属性的类
class Applicant {
private String name;
private String jobProfile;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJobProfile() {
return jobProfile;
}
public void setJobProfile(String jobProfile) {
this.jobProfile = jobProfile;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Validator Class - 检查申请人是否有名字的类
class Validator{
//Implement your code here
public boolean validateName(String name) throws Exception
{
if(getName().length()>0)
{
return true;
}
else{
return false;
}
}
public boolean validateJobProfile(String jobProfile) throws Exception
{
if (getJobProfile().equalsIgnoreCase("Associate") || getJobProfile().equalsIgnoreCase("Clerk") ||
getJobProfile().equalsIgnoreCase("Executive") || getJobProfile().equalsIgnoreCase("Officer"))
{
return true;
}
else{
return false;
}
}
public boolean validateAge(int age) throws Exception
{
if(getAge()>=18 && getAge()<=30)
{
return true;
}
else{
return false;
}
}
public void validate(Applicant applicant) throws Exception
{
if(validateName(getName())==false)
{
throw new InvalidNameException("Invalid Name");
}
if (validateJobProfile(getJobProfile())==false)
{
throw new InvalidJobProfileException("Invalid job post");
}
if (validateAge(getAge())==false)
{
throw new InvalidAgeException("Invalid Age");
}
}
}
测试器类- 创建不同类对象的主类
class Tester {
public static void main(String[] args) {
try {
Applicant applicant= new Applicant();
applicant.setName("Jenny");
applicant.setJobProfile("Clerk");
applicant.setAge(25);
Validator validator = new Validator();
validator.validate(applicant);
System.out.println("Application submitted successfully!");
}
catch (InvalidNameException|InvalidJobProfileException|InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}
解决方案
您的方法声明它throws Exception
。因此,您必须实际捕获Exception
. 如果您只想捕获三个自定义异常中的任何一个,则需要将您的方法声明为仅通过抛出这三个throws InvalidNameException, InvalidJobProfileException, InvalidAgeException
另外,您validateAge
被声明为抛出异常,但实际上从未抛出任何异常。
推荐阅读
- python - 如何混合 groupby.sum() 的结果
- machine-learning - 在隐藏层keras之后添加两层
- javascript - getInitialProps 未按预期从服务器返回数据
- python - 导入“matplotlib”时出错 - Windows Python3.7.4 32 位
- javascript - 无法通过 onClick 事件处理程序访问按钮 id
- scala - 显示单词长度大于8的单词
- html - 如何在输入表单中隐藏提示?
- python - Python google云功能部署失败-Madmom pip包
- vb.net - 如何在 VB 中执行以下操作:月份的最后日期
- c# - ASP.NETCore 模型中的十进制字段格式