如果Catch块本身发生异常,那么如何在C#中处理它?

Atu*_*are 9 c# asp.net

//我在Catch Block中使用了wriiten代码

 try {

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

Hab*_*bib 8

你可以在catch块中放置一个try catch,或者你可以再次抛出异常.它最好是有最终阻止你尝试捕捉,这样即使在catch块中发生异常,finally块代码被执行.

try
  {
  }
catch(Excepetion ex)
  {
     try
        {
        }
     catch
        {
        }
   //or simply throw;
  }
finally
{
  // some other mandatory task
}
Run Code Online (Sandbox Code Playgroud)

最后,块可能无法在某些例外情况下执行.您可能会看到约束执行区域以获得更可靠的机制.


War*_*ock 6

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

让我们假设您有两个层:业务逻辑层(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);
}
Run Code Online (Sandbox Code Playgroud)

BLL:

try
{
  // trying to use DAL
}
catch(MyDALException ex)
{
  // handling
}
catch(Exception ex)
{
   throw new MyBLLException(ex);
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ers 5

try
{
    // Some code here
}
catch (Exception ex)
{
    try
    {
        // Some more code
    }
    catch (Exception ex)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*lap 1

catch 块在任何特定方面都没有特殊之处。您必须使用另一个 try/catch 块或不处理错误。