What are the circumstances under which a finally {} block will NOT execute?

前端 未结 9 2044
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 01:45

In a Java try{} ... catch{} ... finally{} block, code within the finally{} is generally considered \"guaranteed\" to run regardless of what occurs

9条回答
  •  臣服心动
    2020-11-30 02:20

    Another possible instance of a finally block never executing would be due to a design where the method returned before the try block was entered, as in the cases of some very bad code I've seen from time to time:

    public ObjectOfSomeType getMeAnObjectOfSomeType() throws SomeHorrendousException {
        if (checkSomeObjectState()) {
            return new ObjectOfSomeType();
        }
    
        try {
            // yada yada yada...
        } catch (SomeHorrendousException shexc) {
            // wow, do something about this horrendous exception...
        } finally {
            // do some really important cleanup and state invalidation stuff...
        }
    

    I know none of you would ever do this, so I hesitated to add this as a possible scenario, but thought, eh, it's Friday, what the heck ; )

提交回复
热议问题