在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。
- 所有异常都必须是 Throwable 的子类。
- 如果希望写一个检查性异常类,则需要继承 Exception 类。
- 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。
可以像下面这样定义自己的异常类:
class MyException extends Exception{ }
举例说明:
// 自定义异常类
public class TestException extends Exception{
private static final long serialVersionUID = 1L; public TestException() { super(); } public TestException(String msg) { super(msg); } }
// 使用自定义异常抛出异常信息
public class Demo {
public static void main(String[] args){ int a = 12; int b = -2; try { if(b < 0){ throw new TestException("除数为负数"); }else{ System.out.println("result = "+a/b); } } catch (TestException e) { e.printStackTrace(); } } }
示例2:
public class TestException extends Exception{
private static final long serialVersionUID = 1L;
private int value;
public TestException() {
super();
}
public TestException(String msg) {
super(msg);
}
public TestException(String msg,int value){
super(msg);
this.value = value;
}
public int getValue() {
return value;
}
}
public class Test { public int div(int a,int b) throws TestException{ if(b < 0){ throw new TestException("除数为负:",b);// 手动抛出一个自定义异常对象 } return a/b; } }
// 调用测试
public class Demo {
public static void main(String[] args){
Test t = new Test();
try {
int result = t.div(12, 2);
System.out.println("result = "+result);
} catch (TestException e) {
System.out.println(e.toString());
System.out.println("负数是:"+e.getValue());
}
}
}