如何在c#中处理错误代码

时间:2012-09-04 10:13:25

标签: c# windows-phone

我在C#中遇到如何处理try - catch中的错误的问题。

示例我将删除记录的代码写入数据库,但此记录将FK写入另一个表。如何处理?

try
{
     // delete record in database
}
catch (Exception ex)
{
    int error = // how to get this code exception      
}

6 个答案:

答案 0 :(得分:2)

您可能会抓住SQLException而非普通Exception并使用其Number属性

 catch (SqlException ex)
    {
     Console.WriteLine(ex.Number);
    }

答案 1 :(得分:0)

Exception将包含错误类型的详细信息 如果要捕获特定类型的Exception,请在catch中使用该类型。 例如:

 catch (SqlException sqlex)
 {

 }

答案 2 :(得分:0)

您可以将Marshal.GetLastWin32Error()用于Win32.For数据库使用SqlException类。

答案 3 :(得分:0)

try
{  
  //exec delete command
}
catch (SQLException e)
{
  //if SQL error indicates referential integrity violation
    throw ReferentialIntegrityViolationException// or whatever
}

答案 4 :(得分:0)

try
{
    # SQL Stuff
}
catch (SqlException ex)
{
    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
    {
        switch (ex.Errors[0].Number)
        {
            case 547: // Foreign Key violation
                throw new InvalidOperationException("Some helpful description", ex);
                break;
            case 2601: // Primary key violation
                throw new DuplicateRecordException("Some other helpful description", ex);
                break;
            default:
                throw new DataAccessException(ex);
        }
    }

}

根据foreign-key-violation

看看:     how-to-handle-db-exception-in-c-sharp

这将告诉您如何精确定位外键错误。

另请参阅MSDN Row Deletion including foreign keys

关于将级联设置为开启的解释 - 我相信你缺少这个。

答案 5 :(得分:0)

try
{
    // your code to run
}
catch(SqlException ex)
{
    Console.WriteLine(ex.Message);
} 
// Catch all Exceptions
catch(Exception)
{
    Console.WriteLine(Message);
}