finally總是會被執行,即使try中有break、continue、return這樣的語句,如:
public class FinallyTest
{
public static void main(String[] args)
{
int i;
for (i = 0; ;i++)
{
try
{
if (i == 0)
continue;
else if (i == 1)
break;
}
finally
{
System.out.println("loop " + i + " ends");
}
}
try
{
return;
}
finally
{
System.out.println("return ends");
}
}
}
//output
/*
loop 0 ends
loop 1 ends
return ends
*/
另外,從這個例子可以看出,不寫catch,直接try-finally配對也是可以的。