关于异常和异常链

来源:互联网 发布:游戏抽奖软件 编辑:程序博客网 时间:2024/05/20 16:35
package java基础;


//自定义异常 首先异常类会继承Exception或者其他子类
public class CustomizeException extends Exception {
public CustomizeException(String mess) {
super.getMessage();
}
//catch异常链 规则是从小到大,当上面的捕获不了的异常下面再来捕获,同一个异常只能有一个catch块捕获到
//比如当传递-4进入时,会抛出自定义异常。
//当传递0 进去时,就直接被该异常的祖类捕获。
public static void main(String[] args) {
try {
getnumber(0);
} catch (CustomizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("CustomizeException");
} catch (Exception e) {
System.out.print("Exception");
}
}


public static int getnumber(int a) throws CustomizeException {
if (a < 0)
throw new CustomizeException("dsf");
int b = 5 / a;
return b;
}
}