zoukankan      html  css  js  c++  java
  • Java学习随笔之8: 异常处理

    Java 异常主要依赖于 Try, catch, finally, throw, throws

     

    try

    {

    int a = Integer.parseInt(args[0]);

    int b = Integer.parseInt(args[1]);

    int c = a/b;

    System.out.println("The result is: " + c);

     

    }

    catch (IndexOutOfBoundsException ie)

    {

    System.out.println("The Array is out of index");

    }

    catch (NumberFormatException ne)

    {

    System.out.println(ne.toString());

    }

    catch (ArithmeticException ae)

    {

    System.out.println(ae.toString());

    }

    catch (Exception e)

    {

    System.out.println("Unknown exception: " + e.toString());

    }

     

    NullPointerException    //空异常

     

    先捕获小异常, 在捕获大异常 (先子类异常, 在父类异常, 所有 exception在最后, 异常只执行一次)

     

    可以一次捕捉多种类型异常:

    1. 用 | 分割
    2. 捕获多种类型异常时, 异常变量有 隐式的 final所以不能再赋值

    catch (IndexOutOfBoundsException | NumberFormatException  e)

    {

    System.out.println("The Array is out of index");

    }

     

    Finally   回收资源, 不要在 finally 语句里面有 return 或 throw 语句

     

    自动关闭资源的 try 语句, 在try 后面 加 (), 括号里面声明初始化 资源

    try

    (

    BufferedReader br = new BufferedReader(new FileReader("BaseLibrary.java"));          //执行完后自动关闭

    )

    {

    System.out.println(br.readLine());

    }

    10.3 Checked 和 runtime 异常

    Throws exception    -- Checked 异常  在 方法声明后面, 在编译时提示有无异常

    使用 throw 抛出异常, 调用它的方法处理异常

     

    10.4 自定义异常

  • 相关阅读:
    C语言(十八)综合
    C语言(十七)链表
    Redis使用
    fastdb 使用
    CentOS 7.3 安装Oracle 11gR2 64位
    VMWare 12 安装CentOS 7.3 和 Red Hat Enterprise Linux 7.3
    Python学习
    Debian的软件包管理工具命令 (dpkg,apt-get)详解
    Debian8安装Vim8
    VMware12下安装Debian8.5
  • 原文地址:https://www.cnblogs.com/Tomliuxin/p/5872476.html
Copyright © 2011-2022 走看看