java中取消异常提醒_我们如何确定应在Java中检查或取消选中自定义异常?

例外是程序执行期间发生的问题(运行时错误)。当发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。

用户定义的例外

您可以在Java中创建自己的异常,这些异常称为用户定义的异常或自定义异常。

要创建用户定义的异常,请扩展上述类之一。要显示消息,请重写toString()方法,或者通过以String格式传递消息来调用超类参数化的构造函数。MyException(String msg){

super(msg);

}

Or,

public String toString(){

return " MyException [Message of your exception]";

}

然后,在需要引发此异常的其他类中,创建创建的自定义异常类的对象,然后使用throw关键字引发该异常。MyException ex = new MyException ();

If(condition……….){

throw ex;

}

自定义已检查和自定义未检查所有异常都必须是Throwable的子级。

如果要编写由Handle或Delare Rule自动执行的已检查异常,则需要扩展Exception类。

如果要编写运行时异常,则需要扩展RuntimeException类。

示例:自定义检查异常

以下Java程序演示如何创建Custom Checked异常。import java.util.Scanner;

class NotProperNameException extends Exception {

NotProperNameException(String msg){

super(msg);

}

}

public class CustomCheckedException{

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 CustomCheckedException(String name, int age){

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;

}

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

CustomCheckedException obj = new CustomCheckedException(name, age);

obj.display();

}

}

编译时异常

在编译时,以上程序生成以下异常。CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName;

^

1 error

示例:自定义未经检查的异常

如果仅将自定义异常继承的类更改为RuntimeException,它将在运行时引发class NotProperNameException extends RuntimeException {

NotProperNameException(String msg){

super(msg);

}

}

如果您通过使用上面的代码替换NotProperNameException类并运行它来运行先前的程序,它将生成以下运行时异常。

运行时异常Enter the name of the person:

Krishna1234

Enter the age of the person:

20

Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))

at july_set3.CustomCheckedException.(CustomCheckedException.java:25)

at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值