java怎样添加异常_如何在Java中的自定义异常中添加条件?

在构造函数或任何方法中从用户读取值时,可以使用if条件验证这些值。

示例

在下面的Java示例中,我们定义了两个自定义异常类,用于验证名称和年龄。import java.util.Scanner;

class NotProperAgeException extends Throwable{

NotProperAgeException(String msg){

super(msg);

}

}

class NotProperNameException extends Throwable{

NotProperNameException(String msg){

super(msg);

}

}

public class CustomException{

private String name;

private int age;

public static boolean containsAlphabet(String name) {

for (int i = 0; i 

char ch = name.charAt(i);

if (!(ch >= 'a' && ch <= 'z')) {

return false;

}

}

return true;

}

public CustomException(String name, int age){

try {

if (age<0||age>125) {

String msg = "Improper age (not between 0 to 125)";

NotProperAgeException exAge = new NotProperAgeException(msg);

throw exAge;

}else if(!containsAlphabet(name)&&name!=null) {

String msg = "Improper name (Should contain only characters between a to z (all small))";

NotProperNameException exName = new NotProperNameException(msg);

throw exName;

}

}catch(NotProperAgeException e) {

e.printStackTrace();

}catch(NotProperNameException e) {

e.printStackTrace();

}

this.name = name;

this.age = age;

}

public void display(){

System.out.println("Name of the Student: "+this.name );

System.out.println("Age of the Student: "+this.age );

}

public static void main(String args[]) {

Scanner sc= new Scanner(System.in);

System.out.println("Enter the name of the person: ");

String name = sc.next();

System.out.println("Enter the age of the person: ");

int age = sc.nextInt();

CustomException obj = new CustomException(name, age);

obj.display();

}

}

输出结果Enter the name of the person:

Krishna

Enter the age of the person:

136

Name of the Student: Krishna

Age of the Student: 136

july_set3.NotProperAgeException: Improper age (not between 0 to 125)

at july_set3.CustomException.(CustomException.java:31)

at july_set3.CustomException.main(CustomException.java:56)

Output2:

Enter the name of the person:

!23Krishna

Enter the age of the person:

24

Name of the Student: !23Krishna

july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))

Age of the Student: 24

at july_set3.CustomException(CustomException.java:35)

at july_set3.CustomException.main(CustomException.java:56)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值