通过继承Exception类来实现自己的异常类。并使用try-catch来捕获这个异常
class MyException extends Exception {
private static final long serialVersionUID = 1L;
public MyException() {
}
public MyException(String msg) {
super(msg);
}
public MyException(String msg, int x) {
super(msg);
i = x;
}
public int val() {
return i;
}
private int i;
}
public class DemoException {
/**
*方法说明:使用MyException类中默认的构造器
*/
public static void a() throws MyException {
System.out.println("Throwing MyException from a()");
throw new MyException();
}
/**
*方法说明:使用MyException类中带信息的构造器
*/
public static void b() throws MyException {
System.out.println("Throwing MyException from b()");
throw new MyException("Originated in b()");
}
/**
*方法说明:使用了MyException中有编码的构造器
*/
public static void c() throws MyException {
System.out.println("Throwing MyException from c()");
throw new MyException("Originated in c()", 47);
}
public static void main(String[] args) {
try {
a();
} catch (MyException e) {
e.getMessage();
}
try {
b();
} catch (MyException e) {
e.toString();
}
try {
c();
} catch (MyException e) {
e.printStackTrace();
System.out.println("error code: " + e.val());
}
}
} // end :)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。