示例 1: Java 程序创建自定义检查异常
import java.util.ArrayList; import java.util.Arrays; // create a checked exception class class CustomException extends Exception { public CustomException(String message) { // call the constructor of Exception class super(message); } } class Main { ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript")); // check the exception condition public void checkLanguage(String language) throws CustomException { // throw exception if language already present in ArrayList if(languages.contains(language)) { throw new CustomException(language + " already exists"); } else { // insert language to ArrayList languages.add(language); System.out.println(language + " is added to the ArrayList"); } } public static void main(String[] args) { // create object of Main class Main obj = new Main(); // exception is handled using try...catch try { obj.checkLanguage("Swift"); obj.checkLanguage("Java"); } catch(CustomException e) { System.out.println("[" + e + "] Exception Occured"); } } }
输出
Swift is added to the ArrayList [CustomException: Java already exists] Exception Occured
在上面的例子中,我们扩展了
Exception
类来创建一个名为
CustomException 的自定义异常。在这里,我们使用
super()
关键字从
CustomException 类调用
Exception
类的构造函数。
在方法
checkLanguage()
内部,我们检查了异常条件,如果发生异常,try..catch块处理异常。
这里,这是受检异常。我们还可以在 Java 中创建未经检查的异常类。要了解有关已检查和未检查异常的更多信息,请访问 Java 异常。
示例 2: 创建自定义的未检查异常类
import java.util.ArrayList; import java.util.Arrays; // create a unchecked exception class class CustomException extends RuntimeException { public CustomException(String message) { // call the constructor of RuntimeException super(message); } } class Main { ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript")); // check the exception condition public void checkLanguage(String language) { // throw exception if language already present in ArrayList if(languages.contains(language)) { throw new CustomException(language + " already exists"); } else { // insert language to ArrayList languages.add(language); System.out.println(language + " is added to the ArrayList"); } } public static void main(String[] args) { // create object of Main class Main obj = new Main(); // check if language already present obj.checkLanguage("Swift"); obj.checkLanguage("Java"); } }
输出
Swift is added to the ArrayList Exception in thread "main" CustomException: Java already exists at Main.checkLanguage(Main.java:21) at Main.main(Main.java:37)
在上面的例子中,我们扩展了
RuntimeException
类来创建一个未经检查的自定义异常类。
在这里,您可以注意到,我们没有声明任何 try...catch 块。这是因为unchecked异常是在运行时检查的。
除此之外,未检查异常的其他功能与上述程序类似。