这篇文章主要介绍了 java 异常详解及应用实例的相关资料, 需要的朋友可以参考下
java 异常
异常的使用实例(异常分类: Error(是由 JVM 调用系统底层发生的, 只能修改代码) 和 Exception(是 JVM 发生的, 可以进行针对性处理))
1. 如果一个方法内可能出现异常, 那么可以将异常通过 throw 的方式 new 出相应的异常类, 并在方法上 声明 throws 可能抛出的异常类抛给调用者, 调用者可以进行异常捕获, 或者继续抛出异常由 上层调用者继续处理, 如果整个过程都没有将异常进行任何处理, 那么将由 JVM 虚拟机进行默认的处理
2. 调用者可以对异常进行 try()catch(){}的异常处理, 也可以继续在方法后面 throws 该异常, catch 代码块中 如果不处理也可以进行 throw 该异常
3. 运行时异常 RuntimeException 可以不进行显式的异常声明
4. 如果父类中的方法抛出了异常, 如果子类对方法进行重写后也抛出异常, 那么该异常必须不能大于父类的异常类, 如果父类中方法没有抛出异常, 而子类中覆盖的方法却抛出了异常, 那么此时只能进行 try catch 来捕获此异常, 但是也可以将此异常在 catch 代码块中 throw new RuntimeExcetion()进行抛出, 这样方法不用进行 throws 声明
5. 很多时候异常并不需要调用者进行处理, 调用者不一定具有处理能力
6. 异常应该包装成上层调用者可以识别的异常类型, 面向不同的调用者, 报告不同的异常信息, 否者调用者不知道如何处理该异常
在开发中这点十分重要
7.finally 代码块中常常进行资源的释放及关闭操作, 对于打开的资源应该进行反方向的关闭操作, 因为资源可能存在依赖性
8. 如果不进行声明异常, 那么目的是不让调用者进行处理, 让调用者的程序停止, 这样必须修改错误代码
- public class ExceptionDemo {
- public static void main(String[] args) {
- //OutOfMemoryError 内存溢出错误,
- int[] i = new int[1024*1024*1024];
- System.out.println(i[1]);
- //ArrayIndexOutOfBoundsException 索引越界异常
- int[] s = new int[2];
- System.out.println(s[2]);
- Calc calc = new Calc();
- // 假如我们在这里捕获异常
- try {
- calc.run(4, 0);
- calc.run(4, -1);
- } catch (NegativeException e) {// 必须先抛出异常的自定义子类
- e.printStackTrace();
- System.out.println(e.getMessage());
- //throw e;// 可以继续将此异常抛出
- } catch (ArithmeticException e){// 抛出自定义异常类的父类
- e.printStackTrace();
- System.out.println(e.getMessage());
- //throw e;
- } finally {
- System.out.println("finally 肯定会执行到");
- }
- // 如果上面进行了异常捕获, 那么代码可以继续执行, 否者代码不能继续执行
- System.out.println("可以执行到!");
- try {
- calc.run(4, -1);
- } catch (NegativeException e) {
- e.printStackTrace();
- System.out.println(e.getMessage());
- return;
- } finally {
- System.out.println("肯定会执行的");
- }
- System.out.println("执行不到了");// 执行不到此行代码
- }
- }
- /**
- * 自定义异常
- */
- class NegativeException extends ArithmeticException{
- public NegativeException() {
- }
- public NegativeException(String msg) {
- super(msg);
- }
- }
- interface AA{
- public abstract void method();
- }
- class Calc implements AA{
- //ArithmeticException 其实为运行时异常(RuntimeException), 即使不进行 throws 声明, 也可以通过编译
- public int run(int m,int n)throws ArithmeticException,NegativeException{
- if(n==0){
- throw new ArithmeticException("除数不能为 0");
- }else if(n<0){
- throw new NegativeException("除数不能为负数");
- }
- int s = m/n;
- return s ;
- }
- @Override
- public void method() {
- try {
- int p = 4/0;
- } catch (ArithmeticException e) {
- e.printStackTrace();
- throw new RuntimeException();// 将异常继续抛出为运行时异常
- }
- }
- }
来源: http://www.phperz.com/article/18/0227/358774.html