@
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{
new Test().test(1,0);
}catch (ArithmeticException e){
e.printStackTrace();
}
}
// 假设这方法中,处理不了这个异常。方法上抛出异常
public void test(int a, int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();// 主动抛出异常 一般用在方法
}
System.out.println(a/b);
}
/*
// 假设要捕获多个异常:从小到大!
try{// try 监控区域
if(b==0){
throw new ArithmeticException();// 主动抛出异常
}
System.out.println(a/b);
}catch (Error e){// catch(想要捕获的异常类型) 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
} finally {// 处理善后工作
System.out.println("finally");
}// finally 可以不要finally,I/O流操作中关闭资源
*/
}
// 自定义的异常类
public class MyException extends Exception{
// 传递数字>10;
private int detail;
public MyException(int detail) {
this.detail = detail;
}
// toString:异常的打印信息
@Override
public String toString() {
return "MyException{"+detail+‘}‘;
}
}
public class Test {
// 可能会存在异常的方法
public static void test(int a) throws MyException{
System.out.println("传递的参数为:"+a);
if(a>10){
throw new MyException(a);// 抛出
}
System.out.println("ok");
}
public static void main(String[] args) {
try{
test(11);
}catch (MyException e){
System.out.println("MyException=>"+e);
}
}
}
原文:https://www.cnblogs.com/slimety/p/14650301.html