如何在 Java 中决定自定义异常是受检异常还是非受检异常?
异常是在程序执行期间发生的错误(运行时错误)。当发生异常时,程序会突然终止,并且异常发生行之后的代码将不会执行。
用户定义的异常
您可以在 Java 中创建自己的异常,这些异常被称为用户定义的异常或自定义异常。
要创建用户定义的异常,请扩展上述类之一。要显示消息,请覆盖 **toString()** 方法,或者通过以字符串格式传递消息来调用超类的带参数构造函数。
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 的子类。
- 如果您想编写一个受检异常,该异常会由“处理或声明”规则自动强制执行,则需要扩展 Exception 类。
- 如果您想编写一个运行时异常,则需要扩展 **RuntimeException** 类。
示例:自定义受检异常
以下 Java 程序演示了如何创建自定义受检异常。
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 < name.length(); 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.<init>(CustomCheckedException.java:25) at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)
广告