如果在C#的Catch块中发生异常,该如何处理?

9

//我已经在Catch块中编写了代码

 try {

 } catch(Excepetion ex) {
        // I have written code here If Exception Occurs then how to handle it.
 }

以下有几个正确答案,但我可能会重新审视我的代码设计,以确保在catch中不会抛出异常,或者最起码将其封装为另一个方法。多个嵌套的try/catch/finally代码块是一种代码味道--至少对我来说是这样的 :)。 - Jduv
7个回答

8
你可以在catch块中放置try catch,或者只需再次抛出异常。最好在try catch中加入finally块,这样即使在catch块中发生异常,finally块的代码也会被执行。
try
  {
  }
catch(Excepetion ex)
  {
     try
        {
        }
     catch
        {
        }
   //or simply throw;
  }
finally
{
  // some other mandatory task
}

最终块可能无法在某些异常中 执行。您可以查看约束执行区域以获得更可靠的机制。

嵌套的try catch语句似乎是不好的设计。如果抛出异常失败,那么你有更大的问题需要解决。finally语句块总是会执行,所以它不适合放置只有在catch语句块失败时才应该发生的代码。我会选择忽略这个句柄,或者在理想的情况下捕获所有未处理的异常,包括在try catch块中抛出的异常。 - Security Hound

6

最好的方法是为不同层次的应用程序开发自己的异常,并使用内部异常抛出它。它将在你的应用程序的下一层处理。如果你认为,在catch块中可以得到一个新的异常,只需重新抛出此异常而不进行处理。

让我们想象一下,你有两个层次:业务逻辑层(BLL)和数据访问层(DAL),在DAL的catch块中有一个异常。

DAL:

try
{
}
catch(Excepetion ex)
{
  // if you don't know how should you handle this exception 
  // you should throw your own exception and include ex like inner exception.
   throw new MyDALException(ex);
}

BLL:

try
{
  // trying to use DAL
}
catch(MyDALException ex)
{
  // handling
}
catch(Exception ex)
{
   throw new MyBLLException(ex);
}

5
try
{
    // Some code here
}
catch (Exception ex)
{
    try
    {
        // Some more code
    }
    catch (Exception ex)
    {
    }
}

2

对于在catch块中可能会抛出异常的代码行,需添加额外的显式的try..catch块。此外,考虑添加finally块,以确保所有行都能得到执行。同样的问题也可能出现在finally块中。因此,如果您的代码可能会在finally块中抛出异常,也可以在那里添加try..catch块。

try
{
}
catch (Exception ex)
{
    try
    {
        // code that is supposed to throw an exception
    }
    catch (Exception ex1)
    {
    }
    // code that is not supposed to throw an exception       
}
finally
{
    try
    {
        // code that is supposed to throw an exception
    }
    catch (Exception ex1)
    {
    }
    // code that is not supposed to throw an exception       
}

2
双重错误经常发生在设计良好的3g编程语言中。自保护模式和286以来,硬件语言的通用设计是在三次故障时重置芯片。
你可能可以通过设计避免双重错误。在这种情况下,不要因为需要停止处理/向用户报告错误而感到难过。如果你遇到这样一种情况,例如捕获了IO异常(读取/写入数据),然后尝试关闭你正在读取的流,但这也失败了,那么崩溃并警告用户发生了真正异常的情况并不是一个坏的模式。

1
一个catch块并没有什么特别的地方。你要么使用另一个try/catch块,要么不处理错误。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接