如何处理在c#分贝例外 [英] how to handle db exception in c#

查看:142
本文介绍了如何处理在c#分贝例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何处理SQL异常在C#中,反正是有检查什么样的SQL异常,从数据访问层抛出?例如,如果分贝抛出唯一约束异常,或外键的例外,是有什么办法可以从C#抓住它?什么是你正在使用这些数据库异常的异常处理模式

my question is how to handle sql exception in c#, is there anyway to check what kind of the sql exception throws from data access layer? For example, if db throws an unique constraint exception, or foreign key exception, is there any way to catch it from c#? what's the exception handling pattern you are using for these db exception?

推荐答案

有一个看的类//msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.aspx\">documentation,特别是在它的属性:的 SQLException.Number ,例如,应该让您识别的SQLException的类型(唯一约束,外键,...)发生。在VB.NET中,你可以使用条件美中不足的是:

Have a look at the documentation of the SQLException class, in particular, at its properties: SQLException.Number, for example, should allow you to identify which type of SQLException (unique constraint, foreign key, ...) occurred. In VB.NET, you could use conditional catch:

Try
    ...
Catch ex as SqlException When ex.Number = ...
    ...
Catch ex as SqlException When ex.Number = ...
    ...
End Try

在C#中,你将不得不求助于

In C#, you will have to resort to

try {
    ...
} catch (SqlException ex) {
    if (ex.Number == ...) {
        ...
    } else if (ex.Number == ...) {
        ...
    } else {
       throw;   // re-throw exception instead of handling it
    }
}

这篇关于如何处理在c#分贝例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆