//Test.javapublic class Test {
public static void main(String[] args) {
try {
throw new Exception("I am thrown");
}
catch(Exception e) {
System.out.println("I am caught");
e.printStackTrace();
}
finally {
/// line 11
}
System.out.println("Rest parts...."); // line 13
}
} ///:~上例中, 将line 13移到line 11的位置, 与原来的输出结果完全一样.大家都知道finally块是无论异常是否抛出都会执行的一块代码, 既然这样, 那么把这些代码放到finally块中, 与放到外面有什么不同? try...catch...外面的代码不也同样会被执行吗? finally到底用来干嘛? 盼专家解答.
public static void main(String[] args) {
try {
throw new Exception("I am thrown");
}
catch(Exception e) {
System.out.println("I am caught");
e.printStackTrace();
}
finally {
/// line 11
}
System.out.println("Rest parts...."); // line 13
}
} ///:~上例中, 将line 13移到line 11的位置, 与原来的输出结果完全一样.大家都知道finally块是无论异常是否抛出都会执行的一块代码, 既然这样, 那么把这些代码放到finally块中, 与放到外面有什么不同? try...catch...外面的代码不也同样会被执行吗? finally到底用来干嘛? 盼专家解答.
释放资源!eg:public static void Test(string fileName)
{
string fileName;
System.IO.StreamReader sr=null;
try
{
sr=new System.IO.StreamReader(fileName);
}
finally
{
if(sr!=null)
{
sr.Close();
}
}
}
public static void main(String[] args) {
try {
throw new Exception("I am thrown");
}
catch(Exception e) {
System.out.println("I am caught");
e.printStackTrace();
return;
}
finally {
/// line 11
}
System.out.println("Rest parts...."); // line 13
}
} ///
你写一个插入的方法,或者一个删除的方法,
调用这个方法后如果失败,将会有异常,
此时数据库连接是不会自动关闭的,
那么你在finally里写上关闭数据库连接的命令,
这样不管程序执行成功与否
数据库的连接都关闭,
这样可以不必占用太都没必要的资源。
public static void main(String[] args) throws Exception {
boolean error = true;
try {
if(error)
throw new Exception("I am thrown");
}
catch(Exception e) {
System.out.println("I am caught");
e.printStackTrace();
throw e;
}
finally {
/// line 11
}
System.out.println("Rest parts...."); // line 13
}这样11行然后会被执行,而13不会
所以是以上模式,则必须要把line13放到finally以确保被执行.
只这一点就有很大作用
try获取异常如果不throw的话,那就会继续执行try块下面的代码,
如果throw了新的exception那就和return 效果一样