try{}catch{}相關(guān)問題
1 向上拋出exception與不拋出exception的區(qū)別
public class Test1 {
public static void main(String[]args){
System.out.println(test1());
}
public static int test1(){
try{
int a=1/0;
}catch(Exception e){
throw e;
}
return 1;
}
}
這樣會打出exception
public class Test1 {
public static void main(String[]args){
System.out.println(test1());
}
public static int test1(){
try{
int a=1/0;
}catch(Exception e){
//throw e;
}
return 1;
}
}
這樣會打印1
由此可以看出谆刨,向上拋出異常的時(shí)候雕憔,上方調(diào)用函數(shù)是沒辦法得到返回值的。
- 實(shí)際上廉赔,在
throw e;
運(yùn)行完之后,test1()
函數(shù)就跳出了,不會繼續(xù)運(yùn)行return 1;
- 如果沒有
throw e;
異常會被吃掉汉额,繼續(xù)向下運(yùn)行,返回1
2 try{}finally{}語句
try{}代碼塊后可以只接catch榨汤,也可以只接finally蠕搜,但是必須至少要接一個(gè)
public class Test1 {
private static ArrayList<String> arrayList=new ArrayList<>();
public static void main(String[]args){
System.out.println(test1());
}
public static int test1(){
try{
int a=1/0;
}finally{
arrayList.add("haha");
arrayList.add("sdsa");
}
return 1;
}
}
finally語句會執(zhí)行,但是還是會向上拋出異常件余,最終會打印exception
因此try{}finally{}語句相當(dāng)于
try{
}catch(Exception e){
throw e;
}finally{
}
?