如果总是在java执行,finally的目的是什么?
What is the purpose of finally if it always executes in java?
考虑以下 Java 片段:
try{
//Some code to tryout
}
catch(Exception e){
//Catch if there is an exception
}
finally{
//SNIPPET1 that is always executed
}
上面的代码片段基本上等于
try{
//Some code to tryout
}
catch(Exception e){
//Catch if there is an exception
}
//SNIPPET1 that is always executed
我知道 finally 块通常用于关闭网络连接、文件流等。我没有看到将这个关键字引入语言的强烈动机,因为人们可以愉快地也不使用它的程序。
能否请您解释一下引入此关键字的理由?
try {
// statement 1
} catch (Exception e) {
// statement 2
}
// statement 3
如果语句 2 抛出异常,则不会执行语句 3
考虑以下 Java 片段:
try{
//Some code to tryout
}
catch(Exception e){
//Catch if there is an exception
}
finally{
//SNIPPET1 that is always executed
}
上面的代码片段基本上等于
try{
//Some code to tryout
}
catch(Exception e){
//Catch if there is an exception
}
//SNIPPET1 that is always executed
我知道 finally 块通常用于关闭网络连接、文件流等。我没有看到将这个关键字引入语言的强烈动机,因为人们可以愉快地也不使用它的程序。
能否请您解释一下引入此关键字的理由?
try {
// statement 1
} catch (Exception e) {
// statement 2
}
// statement 3
如果语句 2 抛出异常,则不会执行语句 3