zoukankan      html  css  js  c++  java
  • Java异常

    1.什么是异常

    Java代码在运行时期发生的问题就是异常。

    2.异常的继承关系

    Throwable类分为Exception异常和Error错误。

    Exception异常下分为编译期异常和运行期异常,除了RuntimeException之外的异常全都是编译期异常,可以解决。而RuntimeException也就是运行期异常出现,在编译期不会报错,且一旦发生,无法解决问题,只能由程序员修改代码。

    Error错误也是无法处理,只能由程序员修改代码。

    3.抛出异常

    在java中,我们在使用时必须要考虑出现问题的情况,这时,就可以用throw关键字来自己抛出一个指定的异常,来输出一些自己想要输出的信息。

    throw的使用格式为:

    throw new 异常类名(参数);

     1 public static void main(String[] args) {
     2     int[] arr = {1,2,3};
     3     int num = get(arr);
     4     System.out.println(num);
     5 }
     6 public static int get(int[] arr){
     7     if(arr.length<4){
     8         throw new Exception("数组长度不正确!");
     9     }
    10     return arr[3];
    11 }

    而此时只是自己抛出了一个异常,还需要有个处理方式。此时,就要声明异常。

    4.声明异常

    异常的声明就是需要在方法后面使用throws关键字。

    格式为:

    修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2… {   }

     1     public static void main(String[] args) throws Exception  {
     2         int[] arr = {1,2,3};
     3         int num = get(arr);
     4         System.out.println(num);
     5     }
     6     public static int get(int[] arr) throws Exception {
     7         if(arr.length<4){
     8             throw new Exception("数组长度不正确!");
     9         }
    10         return arr[3];

    5.捕获异常

    上述声明异常方法,有一个弊端,就是出现异常后会终止程序,但我们实际业务需求中肯定不能让他结束程序后面的代码不走,所以,这时就要使用捕获异常。

    捕获异常的格式:

    try {

        //需要被检测的语句。

    }

    catch(异常类 变量名) { //参数。

        //异常的处理语句。

    }

    finally {

        //一定会被执行的语句。

    }

     1     public static void main(String[] args){
     2         int[] arr = {1,2,3};
     3         try {
     4             int num = get(arr);
     5             System.out.println(num);
     6         } catch (Exception ex) {
     7             ex.printStackTrace();
     8         }finally {
     9             System.out.println("一定会被执行的语句");
    10         }
    11         System.out.println("Hello world");
    12     }
    13     public static int get(int[] arr) throws Exception {
    14         if(arr.length<4){
    15             throw new Exception("数组长度不正确!");
    16         }
    17         return arr[3];
    18     }

    可以看到,出现异常后,首先是异常出现后,程序结束没有结束,finally里的代码肯定执行,之后的语句也继续执行。

    6.异常处理语句的组合方式

    最常见的就是:try{}catch(){}finally{}

    一个try和多个catch组合:try{}catch(){}catch(){}...使用这种组合时,异常的排序必须是从小到大,否则会出现,父类异常拦截,下面的子类异常无用情况。

    try和finally组合:try{}finally{},因为没有catch语句,所以异常还是jvm抛出处理

  • 相关阅读:
    bzoj3272 Zgg吃东西
    bzoj3894 文理分科
    poj1149 PIGS
    poj1637 Sightseeing tour
    [Wc2007]剪刀石头布
    poj2396 Budget
    [NOI2017]游戏
    CF666E Forensic Examination
    bzoj4889 [Tjoi2017]不勤劳的图书管理员
    CF587F Duff is Mad
  • 原文地址:https://www.cnblogs.com/shenhx666/p/14989987.html
Copyright © 2011-2022 走看看