2011-03-03 81 views
0

我有一個例外相關的問題嘗試,catch異常相關的問題

我有A類,B類 當我打電話從A類B類的一些方法,放在對與嘗試捕捉最後一塊 那麼在A類的try塊中出現異常時會發生什麼情況,然後在調用B類mehod後的那些接下來的步驟中,也會出現異常, 但它顯示最近的異常 我的意思是覆蓋第一個異常B類方法m2()。 而我仍然沒有意識到首先出現的實際異常。

Class A 
{ 
    try{ 
     B b=new B(); 
     b.m1(); 
     b.m2(); 
    } 
    catch(Exception ex) // in catch block here what happens it display the b.m2() exception not the 
         b.m1() exception, while i was thinking it should display first exception 
         when it is calld at m1(); Why so ? 
    { 
     throw; 
    } 
    finally{} 
} 

class B 
{ 
    try 
    { 
     m1(){}; //here comes exception 
     m2(){}; // it also throw some exception 
    } 
    catch(Exception ex) 
    { 
     throw; 
    } 
    finally 
    { 
    } 
} 
+0

這是什麼語言?你應該添加一個標籤來表明語言。此外,你應該適當地縮進代碼。 – 2011-03-03 10:15:40

+0

它的'asp.net,我發佈了一段時間後編輯部分更多的代碼。 – NoviceToDotNet 2011-03-03 10:23:06

回答

2
try{ 
    B b=new B(); 
    b.m1(); 
    b.m2(); 
} 

如果M1拋出一個異常,從不執行平方米。因此,如果m1已經拋出異常,catch語句顯示m2拋出的異常是不可能的。

+0

多數民衆贊成在很奇怪,我處於同樣的困境如何發生,我發佈更多的代碼很快 – NoviceToDotNet 2011-03-03 10:23:40

1

我們需要一些信息。首先,你使用哪種語言?你能告訴我們如何實現m1()m2()?像@Sjoerd說的那樣,m2()將不執行,如果try塊包含m1m2捕獲m1的異常。

例如,在Java中,試試這個代碼:當發生在方法M1的(uncatched)異常

public class A { 
    public void foo() { 
     try { 
      B b = new B(); 
      b.m1(); 
      b.m2(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } finally { 
      // Do something 
     } 
    } 
} 

public class B 
{ 
    public void m1() throws Exception { 
     throw new Exception("m1 exception"); 
    } 

    public void m2() throws Exception { 
     throw new Exception("m2 exception"); 
    } 
} 

public class Test { 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     A a = new A(); 
     a.foo(); 
    } 

} 
1

,則M2將永遠不會被調用。爲了弄清楚,爲什麼它不會在你的情況下工作更多的信息是必要的。它只是不可能的,在你的例子中,m1拋出異常。

我做了一個simular例如像你這樣的,這顯示了預期的行爲:

public class ExceptionCatchExample 
{ 
    public static void main(String[] args) 
    { 
    new ExceptionCatchExample(); 
    } 

    public ExceptionCatchExample() 
    { 
    Controller c = new Controller(); 

    try 
    { 
     c.doMethod1(); 
     c.doMethod2(); 
    } 
    catch (Exception ex) 
    { 
     System.out.println(" Error: " + ex.getMessage()); 
    } 
    } 

} 

class Controller 
{ 
    public void doMethod1() throws Exception 
    { 
    System.out.println("doMethod1()"); 
    throw new Exception("exception in doMethod1()"); 
    } 

    public void doMethod2() throws Exception 
    { 
    System.out.println("doMethod2()"); 
    throw new Exception("exception in doMethod2()"); 
    } 
}