finally总结:
finally代码块:定义一定执行的代码
通常用于关闭资源或者某些一定执行的代码
实例1:finally功能演示
class FuShuException extends Exception
{
FuShuException(String m)
{
super(m);
}
} class Demo
{
public int div(int x,int y) throws FuShuException
{
if(y<0)
{
throw new FuShuException("除数为负数");
}
return x/y;
}
} class ExceptionDemo1
{
public static void main(String args[])
{
Demo d=new Demo();
try
{
int x=d.div(4,-1);
System.out.println("x="+x);
}
catch(FuShuException e)
{
System.out.println(e.toString());
}
finally
{
System.out.println("finally"); //finally存放的是一定会被执行的代码
}
System.out.println("over");
}
}
运行结果:
FuShuException: 除数为负数
finally
over
实例2:
class FuShuException extends Exception
{
FuShuException(String m)
{
super(m);
}
} class Demo
{
public int div(int x,int y) throws FuShuException
{
if(y<0)
{
throw new FuShuException("除数为负数");
}
return x/y;
}
} class ExceptionDemo1
{
public static void main(String args[])
{
Demo d=new Demo();
try
{
int x=d.div(4,-1);
System.out.println("x="+x);
}
catch(FuShuException e)
{
System.out.println(e.toString());
return;
}
finally
{
System.out.println("finally"); //finally存放的是一定会被执行的代码
}
System.out.println("over");
}
}
运行结果:
FuShuException: 除数为负数
finally