Java官方笔记12异常

news2024/11/24 9:42:24

Exception

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

the checked exception

比如,java.io.FileNotFoundException

the error

比如,java.io.IOError

the runtime exception

比如,NullPointerException

error和runtime exception又叫做unchecked exception

Catching and Handling Exceptions

try {
    code
}
catch and finally blocks . . .
try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

使用|catch多个:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

finally

The finally block always executes when the try block exits.

it allows the programmer to avoid having cleanup code accidentally bypassed by a returncontinue, or break.

finally {
    if (out != null) {
        System.out.println("Closing PrintWriter");
        out.close();
    } else {
        System.out.println("PrintWriter not open");
    }
}

finally一定会被执行,除非在try或catch的时候JVM退出了。

The Try-with-resources Statement

为了确保资源被回收,可以使用try-with-resources,类似于Python的with语句:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

OkHttp的示例代码就用到了try-with-resources语句:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

try-with-resources语句也可以跟catch和finally:

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
            int sales = rs.getInt("SALES");
            int total = rs.getInt("TOTAL");

            System.out.println(coffeeName + ", " + supplierID + ", " +
                               price + ", " + sales + ", " + total);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    }
}

语法的区别在于,try-with-resources语句的try后面跟的是小括号(),而捕获异常语句的try后面跟的是大括号{}

try-with-resources语句,小括号里面多个语句以;分隔,但是结尾没有分号:

try(resource1;
    resource2
) {
    statement;
    // 隐式释放资源
}

对比Python with语句来看:

with resource:
    statement

捕获异常语句:

try {
    statement;
}

对于try-with-resources语句,该如何捕获异常呢?

比如:

try (Response response = client.newCall(request).execute()) {
    JSONObject resJson = (JSONObject) JSON.parse(Objects.requireNonNull(response.body()).string());
    String result = resJson.getJSONObject("data").getString("result");
    return JSON.parseObject(result);
}

可以这样写,加个try把整个都包起来:

try {
    try (Response response = client.newCall(request).execute()) {
        JSONObject resJson = (JSONObject) JSON.parse(Objects.requireNonNull(response.body()).string());
        String result = resJson.getJSONObject("data").getString("result");
        return JSON.parseObject(result);
    }
} catch (IOException e) {
    System.out.println(e.getMessage());
}

但更优雅的方式,是直接跟上catch:

try (Response response = client.newCall(request).execute()) {
    JSONObject resJson = (JSONObject) JSON.parse(Objects.requireNonNull(response.body()).string());
    String result = resJson.getJSONObject("data").getString("result");
    result = result.replace("\n", "").replace("\t", "");
    return JSON.parseObject(result);
} catch (IOException e) {
    System.out.println(e.getMessage());
}

try-with-resources语句的try能两用,既with-resources,又catch-exception。

Suppressed Exceptions

If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed.

If try and finally both throw exceptions, then throws the exception thrown from the finally block; the exception thrown from the try block is suppressed.

Throwing Exceptions

使用throws关键字抛异常:

public void writeList() throws IOException {

而在方法内部,则使用throw关键字,注意没有s

public Object pop() {  // EmptyStackException是unchecked,所以这里不用throws
    Object obj;

    if (size == 0) {
        throw new EmptyStackException();
    }

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}

You can throw only objects that inherit from the java.lang.Throwable class.

Note that the declaration of the pop() method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur.

The Throwable hierarchy

Chained Exceptions

把低级别的异常,抛到高级别的异常,进行处理:

try {

} catch (IOException e) {
    throw new SampleException("Other IOException", e);
}

getStackTrace()

catch (Exception cause) {
    StackTraceElement elements[] = cause.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {       
        System.err.println(elements[i].getFileName()
            + ":" + elements[i].getLineNumber() 
            + ">> "
            + elements[i].getMethodName() + "()");
    }
}

Logging

try {
    Handler handler = new FileHandler("OutFile.log");
    Logger.getLogger("").addHandler(handler);
    
} catch (IOException e) {
    Logger logger = Logger.getLogger("package.name"); 
    StackTraceElement elements[] = e.getStackTrace();
    for (int i = 0, n = elements.length; i < n; i++) {
        logger.log(Level.WARNING, elements[i].getMethodName());
    }
}

总结

Most applications you write will throw objects that are instances of Exception. Instances of Error are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.

the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeExceptionError, and their subclasses).

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

异常的好处

1、逻辑代码与异常处理代码解耦:

errorCodeType readFile {
    initialize errorCode = 0;
    
    open the file;
    if (theFileIsOpen) {
        determine the length of the file;
        if (gotTheFileLength) {
            allocate that much memory;
            if (gotEnoughMemory) {
                read the file into memory;
                if (readFailed) {
                    errorCode = -1;
                }
            } else {
                errorCode = -2;
            }
        } else {
            errorCode = -3;
        }
        close the file;
        if (theFileDidntClose && errorCode == 0) {
            errorCode = -4;
        } else {
            errorCode = errorCode and -4;
        }
    } else {
        errorCode = -5;
    }
    return errorCode;
}
readFile {
    try {
        open the file;
        determine its size;
        allocate that much memory;
        read the file into memory;
        close the file;
    } catch (fileOpenFailed) {
       doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (memoryAllocationFailed) {
        doSomething;
    } catch (readFailed) {
        doSomething;
    } catch (fileCloseFailed) {
        doSomething;
    }
}

2、根据调用链抛异常:

method1 {
    errorCodeType error;
    error = call method2;
    if (error)
        doErrorProcessing;
    else
        proceed;
}

errorCodeType method2 {
    errorCodeType error;
    error = call method3;
    if (error)
        return error;
    else
        proceed;
}

errorCodeType method3 {
    errorCodeType error;
    error = call readFile;
    if (error)
        return error;
    else
        proceed;
}
method1 {
    try {
        call method2;
    } catch (exception e) {
        doErrorProcessing;
    }
}

method2 throws exception {
    call method3;
}

method3 throws exception {
    call readFile;
}

3、将异常分类:

catch (FileNotFoundException e) {
    ...
}
catch (IOException e) {
    ...
}
// A (too) general exception handler
catch (Exception e) {
    ...
}

参考资料:

Exceptions https://dev.java/learn/exceptions/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/667377.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Flink流批一体计算(2):Flink关键特性

目录 流式处理 丰富的状态管理 流处理 自定义时间流处理 有状态流处理 通过状态快照实现的容错 流式处理 在自然环境中&#xff0c;数据的产生原本就是流式的。无论是来自 Web 服务器的事件数据&#xff0c;证券交易所的交易数据&#xff0c;还是来自工厂车间机器上的…

优先级队列建立小根堆来解决前K个高频元素(TOP K问题)

目录 场景一&#xff1a;解决前K个高频元素需要解决如下几个问题&#xff1a; 优先级队列PriorityQueue 堆的定义 题目链接 场景二&#xff1a;亿万级数据取前TOP K / 后TOP K 数据 场景一&#xff1a;解决前K个高频元素需要解决如下几个问题&#xff1a; 1.记录每一个元…

【C++】4.工具:读取ini配置信息

&#x1f60f;★,:.☆(&#xffe3;▽&#xffe3;)/$:.★ &#x1f60f; 这篇文章主要介绍读取ini配置信息。 学其所用&#xff0c;用其所学。——梁启超 欢迎来到我的博客&#xff0c;一起学习&#xff0c;共同进步。 喜欢的朋友可以关注一下&#xff0c;下次更新不迷路&…

医院PACS系统的发展历史

PACS全称Picture Archivingand Communication Systems。它是应用在医院影像科室的系统&#xff0c;主要的任务就是把日常产生的各种医学影像&#xff08;包括核磁&#xff0c;CT&#xff0c;超声&#xff0c;X光机&#xff0c;红外仪、显微仪等设备产生的图像&#xff09;通过各…

【工程应用八】终极的基于形状匹配方案解决(小模型+预生成模型+无效边缘去除+多尺度+各项异性+最小组件尺寸)...

我估摸着这个应该是关于形状匹配或者模版匹配的最后一篇文章了&#xff0c;其实大概是2个多月前这些东西都已经弄完了&#xff0c;只是一直静不下来心整理文章&#xff0c;提醒一点&#xff0c;这篇文章后续可能会有多次修改(但不会重新发文章&#xff0c;而是在后台直接修改或…

【MySQL 日志管理、备份与恢复】

目录 一、数据库备份的分类1、从物理与逻辑的角度1.1、物理备份: 对数据库操作系统的物理文件&#xff08;如数据文件&#xff0c;日志文件等&#xff09;的备份1.2、逻辑备份 2、从数据库的备份策略角度3、常见的备份方法3.1、物理冷备3.2、专用备份工具mysqldump 或者 mysqlh…

【Windows系统】windows服务

概述 Microsoft Windows 服务&#xff08;即&#xff0c;以前的 NT 服务&#xff09;使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动&#xff0c;可以暂停和重新启动而且不显示任何用户界面。这种服务非常适合在服…

C++算法:多源最短路径(Floyd)

文章目录 前言一、Floyd算法二、代码实现总结 前言 前文单源最短路径Dijkstra中我们讨论了如何解决有向无环图的最短路径问题&#xff0c;Dijkstra只能解决一个起始点的问题&#xff0c;如果要解决每个顶点到任一顶点的最短路径呢&#xff1f;一个方法就是再循环一次&#xff…

ASEMI代理光宝高速光耦LTV-60L规格,LTV-60L封装

编辑-Z LTV-60L参数描述&#xff1a; 型号&#xff1a;LTV-60L 封装&#xff1a;LSOP-6 储存温度TST&#xff1a;-55~125℃ 工作温度TA&#xff1a;-40~105℃ 隔离电压VISO&#xff1a;5000VRMS 电源电压VCC&#xff1a;7V 平均正向输入电流IF&#xff1a;20mA 输入功…

电脑滤镜软件哪个好 滤镜调色有什么技巧

无论是图片还是视频&#xff0c;滤镜的作用都很大&#xff0c;通过滤镜改变色彩&#xff0c;能让图片或视频增加故事性和美感。电脑滤镜软件哪个好, 电脑滤镜软件有很多&#xff0c;这里我们主要介绍几款视频滤镜软件。滤镜调色有什么技巧&#xff1f;有模板的&#xff0c;我们…

api-hook,更轻量的接口测试工具

目录 前言 现状 api-hook优势 研发介绍 最后 前言 api-hook是一种轻量级的接口测试工具&#xff0c;它基于Python语言编写&#xff0c;可以通过配置文件定义接口测试用例&#xff0c;支持HTTP和HTTPS协议&#xff0c;并提供了灵活的校验机制和数据处理方式。 在网站的开发过…

Tailwindcss 入门

Tailwindcss 是一个功能类优先的 CSS 框架&#xff0c;通过 flex, pt-4, text-center 和 rotate-90 这种原子类组合快速构建网站&#xff0c;而不需要离开你的 HTML。就是记住原子类&#xff0c;不要再自己想 CSS 命名一股脑子写 HTMl 就行了&#xff01; 它与常规的 Bootstra…

佩戴舒适度极好的蓝牙耳机推荐,久戴不累的蓝牙耳机推荐

无论是在日常还是运动的场景下&#xff0c;我们通常都会选择佩戴着耳机&#xff0c;让我们能够释放压力&#xff0c;缓解枯燥的生活。可是&#xff0c;随着市面上的蓝牙耳机层出不穷、各种各样&#xff0c;导致很多小伙伴不知如何选购耳机了&#xff0c;下面我来给大家分享几款…

循踪讲述:成都的夜,有一盏灯为你亮

成都的夜晚总是这样&#xff0c;热闹而梦幻。霓虹灯下的酒吧一条街&#xff0c;你看着手里冒着蒸汽的小龙虾&#xff0c;却心里想着那个人。那个曾经一起在脚手架上挥汗如雨&#xff0c;携手走过平淡岁月&#xff0c;然后在灯红酒绿的生活里逐渐远离的人。 他&#xff0c;一个手…

【数据治理-06】做好数据分类分级,为数据安全有序流动保驾护航

我们常说人以类聚&#xff0c;物以群分&#xff0c;确实是这样&#xff0c;杜威说过“所有知识都是分类”&#xff01;很好理解&#xff0c;分类是认知经济&#xff0c;任何有效分类&#xff0c;都可以极大地节省我们的认知精力。数据分类分级具体说来&#xff0c;其实包含了2个…

欢迎来到 VOXEL WARS!

Sandbox Streams 的全新节目&#xff0c;我们希望你们能参与其中&#xff01; 我们正在寻找 15 名 Voxedit 艺术家&#xff0c;他们将需要抽出 1 小时进行现场表演&#xff08;仅限屏幕共享&#xff09;&#xff0c;并在节奏快速的环境中进行创作&#xff0c;以赢得“最佳快速设…

报道 | 7月国际运筹优化会议汇总

七月召开会议汇总&#xff1a; 30th International Annual EurOMA Conference Location:Leuven Important dates: Conference: July 3, 2023 - July 5, 2023 Details:https://euroma2023.org/ The Equilibrium Computation Workshop at EC Location:Kings College London…

STM32速成笔记—ADC

文章目录 一、什么是ADC二、ADC的用途三、STM32F103ZET6的ADC3.1 ADC通道对应引脚3.2ADC时钟3.3 ADC工作模式3.4 ADC转换时间3.5 ADC校准3.6 ADC转换结果与实际电压的换算 四、ADC配置步骤五、ADC配置程序5.1 ADC初始化程序5.2 软件触发AD转换5.3 读取AD转换结果 六、实战项目6…

运动健身APP开发需要具备哪些功能?

想要开发一款运动健身APP软件&#xff0c;需要具备哪些功能呢&#xff1f; 1、用户注册和登录&#xff1a;用户通过个人信息注册健身APP&#xff0c;登陆之后建立个人账号&#xff0c;以后使用秩序登录自己的账号就可以记录和追踪自己的健身计划和成果。 2、个人…

【新星计划回顾】第六篇学习计划-通过自定义函数和存储过程模拟MD5数据

&#x1f3c6;&#x1f3c6;时间过的真快&#xff0c;这是导师回顾新星计划学习的第六篇文章&#xff01; 最近这段时间非常忙&#xff0c;虽然导师首次参与新星计划活动已经在4月16日圆满结束&#xff0c;早想腾出时间来好好整理活动期间分享的知识点。 &#x1f3c6;&#x1…