java之try catch finally
try{
}catch(Exception e){
}finally{
}
java异常处理在编程中很常见,将可能抛出异常的语句放在try{}中,若有异常抛出,则try{}中抛出异常语句之后的语句不再执行。catch (Exception e) {}抓取异常并进行处理;若无异常,catch中的语句不执行。finally{}中主要做善后工作,如资源回收。无论是否有异常抛出,finally中的语句都会执行。finally中的语句将会在异常捕获机制退出前被调用。
下面来看三个简单的例子:
例1、
public static void test1() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL("").openConnection();
System.out.println("try");
} catch (Exception e) {
System.out.println("exception");
} finally {
System.out.println("finally");
}
System.out.println("end");
}
/*
输出:
exception
finally
end
*/
url地址为空,抛出异常,try中之后的语句不在执行,直接跳到catch{}中,所以输出结果中没有"try"。
例2、
public static void test1() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL("http://www.baidu.com").openConnection();
System.out.println("try");
} catch (Exception e) {
System.out.println("exception");
} finally {
System.out.println("finally");
}
System.out.println("end");
}
/*
输出:
try
finally
end
*/
没有抛出异常,所以catch{}中的语句不执行,所以输出结果中没有"catch"。
例3、
public static void test1() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL("http://www.baidu.com").openConnection();
System.out.println("try");
return;
} catch (Exception e) {
System.out.println("exception");
} finally {
System.out.println("finally");
}
System.out.println("end");
}
/*
输出:
try
finally
*/
因为没有异常抛出,所以catch不执行。因为try中已经有return了,所以之后的语句不在执行。在return之前,按照异常捕获机制,在退出前将调用finally。

浙公网安备 33010602011771号