2011-05-18 54 views
2

我已经在C#中构建了一个应用程序,在捕获异常后我必须中断应用程序。我使用return,但它返回到调用此模块并继续执行的模块。应该做什么?异常处理后需要破解

我的代码看起来喜欢这样的:

class a 
{ 
    b bee=new b{}; 
    bee.read(name); 
    bee.write(name);// don want this to get executed if exception is thrown 
} 

class b 
{ 
    read(string name) 
    { 
     try{} 
     catch 
     { 
      //caught; 

      //what should be put here so that it just stops after dialog 
      // box is shown without moving to the write method? 

     }  

     write(string name) {}     
    } 
} 
+0

您的示例不正确,无法编译,请提供有效的代码示例 – Dyppl 2011-05-18 05:43:10

+1

“break”是什么意思?应用程序应该退出吗?或者只是暂停一会儿? – Oded 2011-05-18 05:44:21

+0

当异常被捕获时,是否要关闭整个应用程序? – Dyppl 2011-05-18 05:44:46

回答

1

你的代码示例是不正确的,但让我们假设你有一个方法这段代码里面:

void M() 
{ 
    b bee=new b(); 
    bee.read(name); 
    bee.write(name);// don want this to get executed if exception is thrown 
} 

如果是这样,你必须赶上例外此方法,不在read方法中。像这样:

void M() 
{ 
    try { 
     b bee=new b(); 
     bee.read(name); 
     bee.write(name);// don want this to get executed if exception is thrown 
    } 
    catch(Exception e) { 
     // Proper error handling 
    } 

} 

read方法你不应该压制异常。要么根本不抓住它们,要么重新抛出它们(或者更好,然后抛出一个新的例外,旧例子是它的InnerExeption)。

如果用这种方法处理方法M中的异常,那么如果在bee.read(name)内发生异常,则不会执行bee.write(name)行。

0

你可以这样做如下

class a 
{ 
    b bee = new b(); 
    try 
    { 
    bee.read(name); 
    bee.write(name); 
    } 
    catch(Exception ex) 
    { 
     //handle error here 
    } 
} 

class b 
{ 
    //These are your method implementations without catching the exceptions in b 
    read 
    write 

} 

如果你发现在该方法中的例外,那么你就不必知道exceution的任何方式该方法的状态没有考虑方法的某种错误状态。无论这是一个布尔返回还是一个在b中可访问的错误代码。

0

为什么不让read方法返回一个值给调用者呢?所以调用者检查从读取返回,如果它是(例如)null它不会写入。或者,您的读取方法可能会返回一个枚举值,告诉调用方read方法退出的条件。

作为另一种选择,调用者可以使用doNotProceed方法实现接口,然后将其自身传递给读取方法。在异常读取调用caller.doNotProceed时,在调用者对象内设置一个内部变量,这告诉它不要继续写入。

你有足够的选择

1

让例外泡了调用方法:

class A { 

    public void Method() { 
    B bee = new B{}; 
    try { 
     bee.Read(name); 
     bee.Write(name); 
    } catch(Exception ex) { 
     // handle exception if needed 
    } 
    } 

} 

class B { 

    public void Read(string name) { 
    try{ 
     ... 
    } catch(Exception ex) { 
     // handle exception if needed 
     throw; 
    } 
    } 

    public void Write(string name) { 
    } 

} 

注:如果您更多钞票应该抓住的,而不是捕捉基类异常的更具体的异常类。没有excpetion参数的catch语句已过时。

0

你可以使用return语句或重新抛出错误,并把另一个父级尝试捕获,但它更好地重构你的代码。