2011-03-03 83 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()"); 
    } 
}