Java考试总结(1)异常。以后继续更新……

第五章 异常
总体:父类 Throwable分为两个子类,其中包括
Error和Exception
Exception包括RuntimeException……(算术异常,空参数异常,数组越界异常)
算术异常:如果是int类型,分母为零是发生报错,如果是double类型的,分母为零时不发生报错,0/0时出现NAN,无穷/0时出现infinite。
//double类型的数进行四则运算得到的结果仍然是double类型
一、解决错误:
try{语句一
}
catch{语句二,出现异常类型或者异常对象
}
finally{语句三
}
//在try中有break或者return循环时,其中finally也要执行一次
//catch子类的顺序:
捕获一般的例外,先排子类后排父类,排兄弟除外;
1、一定有try
2、catch和finally不可以同时省略,一定有其中之一。
二、throw和throws的区别
throws是声明抛出异常(不独立,跟在方法后边),例(方法【参数】throws 异常类(Exception))
而throw是抛出结果异常(独立),Exception e = new Exception();throw e;throw new Exception();
throw +对象;
三、如果父类异常前于子类异常,则打印编译报错

public class Test {
    public int div(int a, int b) {
        try {
            return a / b;
        }catch(Exception e){
            System.out.println(“Exception”);
        }catch(NullPointerException e){
            System.out.println(“ArithmeticException”);
        }
        catch (ArithmeticException e) {
            System.out.println(“ArithmeticException”);
        } finally {
            System.out.println(finally);
        }
        return 0;
    }
    public static void main(String[] args) {
        Test demo = new Test();
        System.out.println(“商是:” + demo.div(9, 0));
    }
}
public class Test {
  public static void main(String[] args) {
    try {
      String s = "5.6";
      Integer.parseInt(s); // 引起一个 NumberFormatException异常

      int i = 0;
      int y = 2 / i;
    }
    catch (Exception ex) {
      System.out.println("NumberFormatException");
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
  }
}

如果子类前于父类的异常会输出相应的异常

public void getCustomerInfo() {
            try {
              // do something that may cause an Exception
            } catch (java.io.FileNotFoundException  ex){
                  System.out.print("FileNotFoundException!");
            } catch (java.io.IOException  ex){
                System.out.print("IOException!");
            } catch (java.lang.Exception  ex){
                 System.out.print("Exception!");
            }
}

输出IOException!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值