如何确定异常是否属于特定类型

我有一段 try catch 代码:

try
{
...
}
catch(Exception ex)
{
ModelState.AddModelError(
"duplicateInvoiceNumberOrganisation", "The combination of organisation and invoice number must be unique");
}

对于这段代码,我试图将一条记录插入到数据库中: dba 已经设置了这条记录,以便数据库检查是否存在重复,如果存在重复,则返回一个错误。目前,正如您所看到的,无论发生什么错误,我都要向模型添加相同的错误。我希望对它进行更改,以便只有当这个错误是由 dba 设置的重复错误引起的时候,才会将它添加到模型中。

下面是我想要捕捉的错误。注意,它在内部异常中。有人能告诉我怎么才能抓住这只吗?

enter image description here

120909 次浏览

before your current catch add the following:

catch(DbUpdateException ex)
{
if(ex.InnerException is UpdateException)
{
// do what you want with ex.InnerException...
}
}

From C# 6, you can do the following:

catch(DbUpdateException ex) when (ex.InnerException is UpdateException)
{
// do what you want with ex.InnerException...
}

You can take a look at the SQLException class -- and check for the contents of the exception's message if it contains what you now see in your inner exception..Something like this:

try
{
//your code here
}
catch (SQLException ex)
{
if (ex.Message.Contains("Cannot insert duplicate key in obj...."))
{
//your code here
}
}

Replace System.Threading.ThreadAbortException with your exception.

try
{
//assume ThreadAbortException occurs here
}
catch (Exception ex)
{
if (ex.GetType().IsAssignableFrom(typeof(System.Threading.ThreadAbortException)))
{
//what you want to do when ThreadAbortException occurs
}
else
{
//do when other exceptions occur
}
}

To get name of the exception you can use

    catch (Exception exc){
if (exc.GetType().FullName == "Your_Exception")
{
// The same can be user for InnerExceptions
// exc.InnerException.GetType().FullName
}
}

Not enough rep to comment. In response to @conterio question (in @Davide Piras answer):

is there a catch "when not" syntax?

There is.

catch (Exception e) when (!(e is ArgumentException)) { }