Java 实例 - 自定义异常
以下实例演示了通过继承 Exception 来实现自定义异常:
TestInput.java 文件
classWrongInputExceptionextendsException{// 自定义的类WrongInputException(Strings){super(s);
}}classInput{voidmethod()throwsWrongInputException{thrownewWrongInputException("Wrong input"); // 抛出自定义的类}}classTestInput{publicstaticvoidmain(String[]args){try{newInput().method();
}catch(WrongInputExceptionwie){System.out.println(wie.getMessage());
}}}
以上代码运行输出结果为:
Wrong input