What is the point of the finally block?

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

Syntax aside, what is the difference between

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

and

try {
}
catch() {
}

x = 3;
         


        
16条回答
  •  -上瘾入骨i
    2020-12-30 21:06

    @iAn and @mats:

    I would not "tear down" anything in finally {} that was "set up" within the try {} as a rule. Would be better to pull the stream creation outside of the try {}. If you need to handle an exception on stream create this could be done in a greater scope.

    StreamReader stream = new StreamReader("foo.bar");  
    try {
        mySendSomethingToStream(stream);
    }
    catch(noSomethingToSendException e) {
        //Swallow this    
        logger.error(e.getMessage());
    }
    catch(anotherTypeOfException e) {
        //More serious, throw this one back
        throw(e);
    }
    finally {
        stream.close();  
    }
    

提交回复
热议问题