• JavaSE: 异常的避免与捕获


    异常的避免:

      尽量使用if条件判断来避免异常的发生

    这样做的缺点:

      代码臃肿,可读性差

    示例:

    class ExceptionPreventTest{

      main(){

        // 算术异常

        int ia = 10;

        int ib = 0;

        if ( 0 != ib){

          print(ia / ib);

        }

        // 数组下标越界异常

        int[] arr = new int[5];

        int pos = 5;

        if( pos >= 0 && pos < 5){

          print(arr[pos]);

        }

        // 空指针异常

        String str = null;

        if (null != str){

          print(str.length());

        }

        // 类型转换异常

        Exception ex = new Exception();

        if (ex instanceof IOException){

          IOException ie = (IOException) ex;

        }

        

        // 数字格式异常

        String str2 = "123a";

        if (str2.matches (\d+)){

          print(Integer.parseInt(str2));

        }

        print("程序总算正常结束了!")

      }

    }

    异常的捕获

    语法格式:

    try{

      编写可能发生异常的代码

    }catch(异常类型 引用变量名){

      编写针对该类异常的处理代码

    }

    ...

    finally{

      编写无论是否发生异常都要执行的代码

    }

    示例:

    class ExceptionCatchTest{

        main(){

          // 创建一个FileInputStream类型的对象与 d:/a.txt 文件关联,打开文件

          FileInputStream fis = null;

          try{

            print "1";

            // 当程序执行过程中发生了异常后,直奔catch分支进行处理 ("2" 不会执行)

            fis = new FileInputStream("d:/a.txt");

            print "2";

          }catch (FileNotFoundException e){

            print "3";

            e.printStackTrace();

            print "4";

          }

          // 关闭文件

          try{

            print "5";

            fis.close();

            print "6";

          } catch (IOException e){

            print "7";

            e.printStackTrace();

            print "8";

          } catch (NullPointerException e){

            e.printStackTrace();

          } 

        }

    }

      手动处理异常和没有处理的区别:

        代码是否可以继续向下执行

      注意事项:

        <1>catch (Exception e){

          e.printStackTrace();

         } 

              不推荐这样的写法,因为可读性差

        <2> 在异常捕获时,小Exception的类型 需要放在 大Exception类型的前面

  • 相关阅读:
    性能测试——Jmeter基本用法概述
    Postman-newman基础用法
    数据库基础总结
    性能测试概述
    pytest+allure生成测试报告
    CSS入门基础
    HTML基础知识总结
    robotframework:无法导入资源Not a valid file or directory to import
    robotframework及官方编辑器RIDE的安装与配置
    常用排序算法
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/14858766.html
Copyright © 2020-2023  润新知