理解try-catch-finally块的工作有困难

Kan*_*son 3 java

如果我错了,请纠正我,但是,我相信try块中的语句首先被执行,然后,如果发生任何异常,finally块中的语句将被执行,然后catch块中的语句被执行.如果没有发生异常,则一旦try执行块中的语句并跳过catch块中的语句,就会执行finally块中的语句.

如果我的上述概念没有错,那么我不明白为什么这段代码不起作用:

// sock is an object of the class Socket
public void run() {
    try {
        in = sock.getInputStream();
        scan = new Scanner(in);
        out = sock.getOutputStream();
        pw = new PrintWriter(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        sock.close();
    }   
}
Run Code Online (Sandbox Code Playgroud)

它仍然说我需要在finally块中包含语句try-catch.

Bli*_*lip 6

没有!try块中的语句首先执行.然后,如果发生任何异常,则执行catch块语句.和finally块最后执行.finally即使try块中发生异常,也会执行块.换句话说,如果没有异常发生,则首先try执行该finally块然后执行该块.

  • @KaneWilliamson我认为你没有正确阅读我的答案.你说过**1`Try`,2`final`和3`catch`**.但我说**1`尝试`,2`捕获`和3`最终`** (4认同)