java異常踩坑心得
我們使用如下程式碼來故意產生一個異常,下面的程式碼由於被除數是0,因此將會產生算術異常
int s=10/0;
下面我們來進行我們的實驗。
1.
public static String a()
{
try {
int s=10/0;
return "aaaa";
} catch (Exception e) {
System.out.println("bbbb");
return "cccc";
}
}
public static void main(String[] args) {
System.out.println(a() );
}
執行結果:
執行到int s = 10/0;就會被捕獲到異常,直接跳到catch塊中,根本不會去執行列印aaaaa,因此只執行列印bbbbb和ccccc
2.
public static String a()
{
try {
int s=10/0;
return "aaaa";
} catch (Exception e) {
System.out.println("bbbb");
return "cccc";
} finally {
System.out.println("lllll");
return "finally" ;
}
}
public static void main(String[] args) {
System.out.println(a());
}
執行結果:
雖然在catch塊中寫了return語句,但是由於要執行finally塊中的程式碼,因此方法暫時還不能return,而是去執行了finally中的語句和finally中的return,本來應該去將catch塊中的return語句置於finally之後執行的,但是由於finally中有return語句,因此還沒來得及執行catch塊中的return,方法就已經返回了
3.
public static String a ()
{
try {
int s=10/0;
return "aaaa";
} catch (Exception e) {
System.out.println("bbbb");
return "cccc";
} finally {
System.out.println("lllll");
}
}
public static void main(String[] args) {
System.out.println(a());
}
執行結果:
為了驗證上一條所說的,我們將finally塊中的return語句去掉,發現這次果然執行了catch塊中的return語句,證明了catch塊中的return語句確實被置於finally塊之後執行了
4.
public static String a()
{
try {
int s=10/0;
return "aaaa";
} catch (Exception e) {
System.out.println("bbbb");
} finally {
System.out.println("lllll");
return "finally";
}
}
public static void main(String[] args) {
System.out.println(a());
}
執行結果:
這個沒什麼好說的,先執行了catch塊再執行了finally塊
5.
public static String a()
{
try {
int s=10/0;
} catch (Exception e) {
System.out.println("bbbb");
return b();
} finally {
System.out.println("lllll");
return "finally";
}
}
public static String b()
{
System.out.println("ooooooo");
return "mmmmm";
}
public static void main(String[] args) {
System.out.println(a());
}
執行結果:
這裡我們將剛才直接返回一個字串改成了返回一個方法的執行結果,和之前一樣,catch塊中的return依然因為被置於在finally的return後而沒能執行
6.
public static void a()
{
try {
b();
} catch (Exception e) {
System.out.println("aaaaa");
}
}
public static void b()
{
try {
throw new Exception("bbbbb");
} catch (Exception e) {
System.out.println("ccccc");
}
}
public static void main(String[] args) {
a();
}
執行結果:
這裡在try塊中捕獲到了產生的異常,並且已經在b()方法的catch塊中對異常進行了處理,那麼在a()方法中就不會再次捕獲到異常了,注意,throw是顯示一個異常,而throws是向上級丟擲一個異常讓上級去進行try catch處理,兩者不要混淆
7.
public static void a()
{
try {
try {
int b = 10/0;
} catch (Exception e) {
System.out.println("aaaaa");
}
} catch (Exception e) {
System.out.println("bbbbb");
}
}
public static void main(String[] args) {
a();
}
執行結果:
和上一條類似,已經在第一個try catch塊中對異常處理完畢了,就不會再在外部的try塊中捕獲到異常了
8.
public static void a() throws Exception
{
try {
int a = 10/0;
} catch (Exception e) {
System.out.println("bbbbb");
}
}
public static void main(String[] args) {
try {
a();
} catch (Exception e) {
System.out.println("ccccc");
e.printStackTrace();
}
}
執行結果:
依然和上面兩條類似,已經在內部的try catch塊中對異常處理完畢,即使向上級丟擲了異常,上級再try,也不會捕獲到異常,因此不會執行上級的catch塊