如何创建自定义异常?(How to create custom exceptions in Java?)
class WrongInputException extends Exception { // 自定义的类
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong input"); // 抛出自定义的类
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
简单明了 我们只需要自定义一个继承Exception的类。然后再我们的类中抛出这个自定义的异常检查类。最后在测试类中获取并抛出这个异常即可。

浙公网安备 33010602011771号