欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Java实例-自定义异常

来源: javaer 分享于  点击 12443 次 点评:283

Java实例-自定义异常


Java 实例 Java 实例

以下实例演示了通过继承 Exception 来实现自定义异常:

TestInput.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());
}
}
}

以上代码运行输出结果为:

Wrong input

Java 实例 Java 实例

用户点评