最终嵌套在Exceptions中的行为

kur*_*der 1 java

今天在工作中,我不得不查看一个类似于这个模拟示例的代码片段.

package test;

import java.io.IOException;
import org.apache.log4j.Logger;

public class ExceptionTester {

    public static Logger logger = Logger.getLogger(ExceptionTester.class);

public void test() throws IOException {
    new IOException();
}

public static void main(String[] args) {
    ExceptionTester comparator = new ExceptionTester();
    try {
        try {
            comparator.test();
        } finally {
            System.out.println("Finally 1");
        }
    } catch(IOException ex) {
        logger.error("Exception happened" ex);
            // also close opened resources
    } 
    System.out.println("Exiting out of the program");
}
Run Code Online (Sandbox Code Playgroud)

}

try

catch

它正在打印以下输出.我期望编译错误,因为内部IOException没有catch块.

Finally 1
Exiting out of the program

我不明白为什么 package test;

import java.io.IOException;
import org.apache.log4j.Logger;

public class ExceptionTester {

    public static Logger logger = Logger.getLogger(ExceptionTester.class);

public void test() throws IOException {
    new IOException();
}

public static void main(String[] args) {
    ExceptionTester comparator = new ExceptionTester();
    try {
        try {
            comparator.test();
        } finally {
            System.out.println("Finally 1");
        }
    } catch(IOException ex) {
        logger.error("Exception happened" ex);
            // also close opened resources
    } 
    System.out.println("Exiting out of the program");
}
Run Code Online (Sandbox Code Playgroud)

} 被外部try区块抓住了.如果有人能够解释这一点,我将不胜感激,特别是通过引用堆栈展开过程

Ben*_*igt 6

finally块表示必须在正常和异常条件下完成的任务.

例子:你带一个面试候选人去吃午饭.在午餐时,你发现他被警方通缉谋杀.例外!午餐结束了,面试完全是亏损,但是......你仍然需要支付午餐费用.

try {
    meetForLunch(interviewCandidate);
}
finally {
    lunchBill.pay();
}
Run Code Online (Sandbox Code Playgroud)

请注意,支付午餐并没有照顾到例外情况,你仍然需要在面试时对凶手做些什么.在处理损坏控制之前,这只是一个松散的结束.

大多数finally块都以这种方式使用:无论是否成功保存数据,都需要关闭文件,无论交易是否被批准,都需要关闭数据库连接等.

并且异常以其快乐的方式向外延伸,在封闭范围内寻找匹配的捕获块.

请注意,finally块将始终运行,除非在try块仍在执行时进程结束.

  • @Stephen:我想你错过了最后一句话. (5认同)