Java官方笔记12异常

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 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值