finally子句用来说明必须执行的语句,无论TRY程序块中是否抛出例外,FINALLY程序块中的语句都将会被执行..
public class ExampleFinallyException
{
public static void main(String[] args)
{
System.out.println("Hello World!");
try
{
int x=0;
int y=28;
int z=y/x;//除数为零..
System.out.println("The value of y/x is "+z);
}
catch (ArithmeticException e)
{
System.out.println("this program has caught an Arithmetic Exception!");
}
finally
{
System.out.println("Excuting the finally sub sentence!");
try
{
String name=null;
if(name.equals("wangneng"))
System.out.println("My name is wangneng!");
}
catch (Exception e)
{
System.out.println("this program has caught an Arithmetic Exception once more! ");
}
finally
{
System.out.println("Excuting the finally sub sentence once more!");
}
}
}
}
finally子句通常还可以与break.continue and return语句一起使用.当try程序地中出现了break.continue and return等语句时,程序必须先执行finally子句,才能最终离开程序块..
class BreakAndFinally
{
public static void main(String[] args)
{
System.out.println("Hello World!");
while(true)
{
try
{
System.out.println("this program wanna go out of this while sub sentence by break !");
break;
}
finally
{
System.out.println("this program must execute me before leave the while sub sentence");
}
}
}
}