简体   繁体   English

为什么挡块没有被触发?

[英]Why is the catch block not being triggered?

I am trying to log errors to a file but I can't seem to get the catch block to run when an error occurs. 我正在尝试将错误记录到文件中,但出现错误时似乎无法使catch块运行。 Here is an example of the code: 这是代码示例:

try  
{  
     cmd.ExecuteNonQuery();  
}  
catch (MySQLException ex)  
{   
     //run some logging code  
}  
finally  
{  
     //clean up the resources  
}  

The problem is when there is an exception, I get the error thrown from the built in webserver that its an unhandled exception. 问题是当有异常时,我从内置的Web服务器中抛出了一个错误,即未处理的异常。 When I debug the code stops at the exception then continues on to the finally block. 当我调试代码时,代码会在异常处停止,然后继续执行finally块。 Can someone point me in the right direction here? 有人可以在这里指出正确的方向吗?

ExecuteNonQuery() throws an exception of type SqlException . ExecuteNonQuery()抛出类型为SqlException

So I'm not sure what MySQLException is, but you need to be catching an SqlException . 所以我不确定什么是MySQLException ,但是您需要捕获SqlException

Look at this for extra info: 查看此以获得更多信息:

It seems like the exception thrown is not not of type MySQLException or any exception derived from it. 似乎抛出的异常不是MySQLException类型或从其派生的任何异常。 So the catch block never never catches it and the finally block is executed directly! 因此catch块永远不会捕获它,而finally块将直接执行!

To check what kind of exception was raised, modify the code to: 要检查引发了哪种异常,请将代码修改为:

try  
{  
   cmd.ExecuteNonQuery();  
}  
catch (MySQLException ex)  
{   
   //run some logging code  
}  
catch (Exception ex)
{
   // any other exception will be handled here
}
finally  
{  
   //clean up the resources  
} 

That method can throw different types of exceptions 该方法可以引发不同类型的异常

  • InvalidCastException InvalidCastException
  • SqlException SqlException异常
  • IOException IOException
  • InvalidOperationException InvalidOperationException
  • ObjectDisposedException ObjectDisposedException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM