简体   繁体   English

C#,Catch异常

[英]C#, Catch Exception

I get a Exception type using 我使用了一个Exception类型

catch(Exception e){
  log.Error(e.GetType()); // it write 'System.Data.EntityException'
}

so I change my code to catch that exception, 所以我改变我的代码以捕获该异常,

try{
...
}catch(EntityException a){
  // need to do something
  log.Error("I got it!");
}catch(Exception e){
  log.Error("No");
}

and the code write only "No". 并且代码只写“否”。

How can I catch the EntityException before reach Exception? 如何在达到Exception之前捕获EntityException?

Thanks 谢谢

The code you have should work correctly, provided there isn't another EntityException type defined within the current set of using statements for that file or namespace. 如果在该文件或命名空间的当前使用语句集中没有定义另一个EntityException类型,那么您所拥有的代码应该可以正常工作。

Try fully qualifying the type, as in the following: 尝试完全限定类型,如下所示:

try{
...
}catch(System.Data.EntityException a){
  // need to do something
  log.Error("I got it!");
}catch(Exception e){
  log.Error("No");
}

I was having the same problem, and the accepted answer here wasn't working for me. 我遇到了同样的问题,这里接受的答案对我不起作用。 While EntityException is fully qualified as System.Data.EntityException, it's actually in the System.Data.Entity assembly (See http://msdn.microsoft.com/en-us/library/system.data.entityexception(v=vs.110).aspx ), so the project needs a reference to System.Data.Entity before Intellisense will recognize System.Data.EntityException in your code. 虽然EntityException完全限定为System.Data.EntityException,但它实际上在System.Data.Entity程序集中(请参阅http://msdn.microsoft.com/en-us/library/system.data.entityexception(v=vs。 110).aspx ),因此在Intellisense识别代码中的System.Data.EntityException之前,项目需要引用System.Data.Entity。

匹配异常的第一个“catch”是激活的那个。

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

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