}
} 运行结果 Exception in thread “main” java.lang.ArithmeticException: / by zero at com.ExcptionTest.main(ExcptionTest.java:6) ====运行前====错误的定义 错误是很难处理的,比如内存溢出,不能够通过异常处理来解决。try-catch-finally的作用
try : 检测不安全的代码块(发现异常)catch: 异常处理代码finally:不管出现或者不出现异常都会执行的代码其中catch和finally可以省略,但是try不能可以多个catch块catch的异常,父类异常的catch块在子类异常之后可以catch任何异常catch CheckedException时,try块中必须存在可能引发该异常的代码,否则编译错误如果catch或者finally块中存在异常,则需要再次处理下面我来举个”栗子”:public class Extceptions { public static void main(String[] args) { try{
int a=10/0; //现在try存在异常,它会直接跳到catch中 System.out.println("我在try");}catch(ArithmeticException e){ System.out.println(“我在catch”); }finally{ //finally不管出现或者不出现异常都会执行的代码 System.out.println(“我在final”); }
}
}
输出结果 我在catch我在finalfinally&return
是否 出现异常都会执行finally是否在正常代码和异常处理代码中return,仍然会先执行finally再return不会执行finally的情况:System.exit(0);我来举个”栗子”:public class Extceptions { public static void main(String[] args) { try{ int b = 10/0;
System.out.println("try,try"); return;}catch(ArithmeticException e){
System.out.println("catch catch");// System.exit(0); 这个是结束虚拟机,所有就不会运行到finally这一步了 return; }finally{ System.out.println(“finally”); return;
} }
}
输出结果 catch catchfinally示例
public void test throws 异常1,异常2,异常3{
}
所谓层层抛出异常
就是 catch中,再次用throw抛出异常举”栗子”
public class Throw1 { public static void main(String[] args) { try{ bang(130); }catch(Exception e){ e.printStackTrace();
} } private static void bang(int x)throws IOException{ big(x); } private static void big(int a)throws IOException{ if(a>120){ throw new IllegalArgumentException(“参数异常,年龄最大不超过120”); }
throw new IOException(“”);
}
}
总结
throw用于方法体中,用来抛出一个实际的异常对象,使用throw后,要么使用try catch捕获异常,要么使用throws声明异常throws用于方法声明处,用来声明该方法可能发生的异常类型,可以是多个异常类型,用来强制调用该方法时处理这些异常抽象方法也可以使用throws,所以说并不是有throw才有throws如果使用throw关键字抛异常,一定不要使用Exception,不能很好标记异常类型如果throw要抛出与业务逻辑有关的异常,需要使用自定义异常类输出结果
java.lang.IllegalArgumentException: 参数异常,年龄最大不超过120 at Exception2.Throw1.big(Throw1.java:19) at Exception2.Throw1.bang(Throw1.java:15) at Exception2.Throw1.main(Throw1.java:8)自定义异常类中往往不写其他方法,只重载需要使用的构造方法
自定义异常示例
public class BusinessException extends IOException{public BusinessException() { super(); } public BusinessException(String message, Throwable cause) { super(message, cause);
} }
在程序中使用自定义异常大致可以分为一下几步
创建自定义异常类在方法中通过throw 关键字抛出自定义异常如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理,否则在方法的声明处通过throws关键字声明该异常调用throws声明该异常的方法时,使用try catch捕获自定义的异常类型,并在catch中进行处理