What is the point of the finally block?

后端 未结 16 1219
长情又很酷
长情又很酷 2020-12-30 20:19

Syntax aside, what is the difference between

try {
}
catch() {
}
finally {
    x = 3;
}

and

try {
}
catch() {
}

x = 3;
         


        
16条回答
  •  无人及你
    2020-12-30 20:54

    The finally block is in the same scope as the try/catch, so you will have access to all the variables defined inside.

    Imagine you have a file handler, this is the difference in how it would be written.

    try
    {
       StreamReader stream = new StreamReader("foo.bar");
       stream.write("foo");
    }
    catch(Exception e) { } // ignore for now
    finally
    {
       stream.close();
    }
    

    compared to

    StreamReader stream = null;
    try
    {
        stream = new StreamReader("foo.bar");
        stream.write("foo");
    } catch(Exception e) {} // ignore
    
    if (stream != null)
        stream.close();
    

    Remember though that anything inside finally isn't guaranteed to run. Imagine that you get an abort signal, windows crashes or the power is gone. Relying on finally for business critical code is bad.

提交回复
热议问题