示例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 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 Exception。
示例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 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块。这是因为未检查的异常是在运行时检查的。
除此之外,未检查异常的其他功能与上述程序类似。