如何在Java代码中解决未处理的异常错误

huangapple go评论60阅读模式
英文:

How to remove Unhandled Exception Error in the Java Code

问题

我是Java的新手正在尝试处理异常代码在我遇到**未处理的异常错误**之前一切都对我来说都很好有谁可以帮忙纠正代码并告诉我错误在哪里以便我以后不会再犯同样的错误

**异常类** - 创建用于获取不同异常消息的类

     // 实现用户定义的异常类
    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;
        }
    }
    

**验证器类** - 用于检查申请人是否有姓名
    
    class Validator{
    	// 在这里实现你的代码
    	public boolean validateName(String name) throws Exception
    	{
    	    if(name.length() > 0)
    	    {
    		    return true;
    	    }
    	    else{
    		    return false;
    	    }
        }

	    public boolean validateJobProfile(String jobProfile) throws Exception
	    {
		    if (jobProfile.equalsIgnoreCase("Associate") || jobProfile.equalsIgnoreCase("Clerk") || 
            jobProfile.equalsIgnoreCase("Executive") || jobProfile.equalsIgnoreCase("Officer"))
		    {
			    return true;
		    }
		    else{
			    return false;
		    }
	    }

	    public boolean validateAge(int age) throws Exception
	    {
		    if(age >= 18 && age <= 30)
		    {
			    return true;
		    }
		    else{
			    return false;
		    }
	    }

	    public void validate(Applicant applicant) throws Exception
	    {
		    if(validateName(applicant.getName()) == false)
		    {
			    throw new InvalidNameException("Invalid Name");
		    }
		    if (validateJobProfile(applicant.getJobProfile()) == false)
		    {
			    throw new InvalidJobProfileException("Invalid job post");
		    }
		    if (validateAge(applicant.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());
            }
        }
    }

以上是您提供的代码的中文翻译。如果您有任何其他翻译需求,请随时提问。

英文:

I am new to Java and trying my hands on the exception handling code. Everything was fine to me until I get unhandled exception error. Can anyone please help me to correct the code and tell my mistake so that I can never commit again?

Exception Class - Created this to retrieve message for different exceptions

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

Applicant Class - Class to set and get attributes of Applicant

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 to check if the Applicant has a name or not

class Validator{
//Implement your code here
public boolean validateName(String name) throws Exception
{
if(getName().length()&gt;0)
{
return true;
}
else{
return false;
}
}
public boolean validateJobProfile(String jobProfile) throws Exception
{
if (getJobProfile().equalsIgnoreCase(&quot;Associate&quot;) || getJobProfile().equalsIgnoreCase(&quot;Clerk&quot;) || 
getJobProfile().equalsIgnoreCase(&quot;Executive&quot;) || getJobProfile().equalsIgnoreCase(&quot;Officer&quot;))
{
return true;
}
else{
return false;
}
}
public boolean validateAge(int age) throws Exception
{
if(getAge()&gt;=18 &amp;&amp; getAge()&lt;=30)
{
return true;
}
else{
return false;
}
}
public void validate(Applicant applicant) throws Exception
{
if(validateName(getName())==false)
{
throw new InvalidNameException(&quot;Invalid Name&quot;);
}
if (validateJobProfile(getJobProfile())==false)
{
throw new InvalidJobProfileException(&quot;Invalid job post&quot;);
}
if (validateAge(getAge())==false)
{
throw new InvalidAgeException(&quot;Invalid Age&quot;);
}
}
}

Tester Class - Main Class where objects of different classes are created

class Tester {
public static void main(String[] args) {
try {
Applicant applicant= new Applicant();
applicant.setName(&quot;Jenny&quot;);
applicant.setJobProfile(&quot;Clerk&quot;);
applicant.setAge(25);
Validator validator = new Validator();
validator.validate(applicant);
System.out.println(&quot;Application submitted successfully!&quot;);
} 
catch (InvalidNameException|InvalidJobProfileException|InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}

答案1

得分: 0

你的方法声明了throws Exception。因此,你实际上必须捕获Exception。如果你只想要捕获这三个自定义异常中的任意一个,你需要通过throws InvalidNameException, InvalidJobProfileException, InvalidAgeException来声明你的方法只会抛出这三个异常之一。

另外,你的validateAge方法被声明为会抛出异常,但实际上从未抛出任何异常。

英文:

Your method declares that it throws Exception. Thus, you have to actually catch Exception. If you only want to have to catch either of the three custom exceptions, you need to declare your method as only throwing those three via throws InvalidNameException, InvalidJobProfileException, InvalidAgeException

Plus, your validateAge is declared as throwing an exception, but never actually does throw anything.

答案2

得分: 0

你的方法需要指定它们实际抛出的异常。目前你只是写了它们抛出通用的 Exception,然后在主程序中没有捕获这些异常。请将代码从:

public void validate(Applicant applicant) throws Exception{...}

修改为:

public void validate(Applicant applicant) throws InvalidNameException, InvalidJobProfileException, InvalidAgeException{...}

对于其他方法,你需要类似地进行修改。

英文:

Your methods need to specify which exceptions they are actually throwing. At the moment you are simply writing that they throw the general Exception, which you then don't catch in your main.
Change

public void validate(Applicant applicant) throws Exception{...}

to

public void validate(Applicant applicant) throws InvalidNameException, InvalidJobProfileException, InvalidAgeException{...}

For the other methods you need to do it similarly.

huangapple
  • 本文由 发表于 2020年9月30日 22:39:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64139954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定