本文介绍了您如何通过“使用”捕获异常?在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

using (var conn = new SqlConnection("..."))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "...";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // ...
            }
        }
    }
}

我习惯为我的数据访问编写try / catch / finally块,但是,我很容易接触到使用,这似乎是一种更简单的方法。但是,我试图弄清楚如何捕获可能发生的异常。

I'm used to writing try/catch/finally blocks for my data access, however, I'm being exposed to "using" which seems like a much simpler method of doing this. However, I'm trying to figure out how to catch exceptions that may occur.

能否请您举一个如何捕获异常的示例?

Could you please give me an example of how you'd catch exceptions?

编辑添加:

我被引导认为使用是替代我的try / catch / finally块。我了解使用不会捕获异常。

I'm being led to believe that "using" is a replacement for my try/catch/finally blocks. I understand that using doesn't catch exceptions. So how is this a replacement?

推荐答案

使用不是设计好的方法。捕捉异常;它旨在为您提供一种简便的方法,将 try / finally 包裹在需要处理的物体周围。如果您需要捕获和处理异常,则需要将其扩展为完整的 try / catch / 最终或在整个过程中放置​​一个 try / catch

using isn't designed to catch exceptions; it's designed to give you an easy way to wrap a try/finally around an object that needs to be disposed. If you need to catch and handle exceptions then you'll need to expand it into a full try/catch/finally or put a containing try/catch around the whole thing.

要回答您的修改(使用替代了尝试 / 捕获 / 最终?)然后不,它不是。在大多数情况下,使用一次性资源时,您不会在那里处理异常,然后因为通常没有任何有用的处理方法。因此,它提供了一种简便的方法,可以确保无论您要做什么都可以正常工作,对资源进行清理。

To answer your edit (is using a replacement for try/catch/finally?) then no, it isn't. Most of the time when using a disposable resource you aren't going to handle the exception there and then because there's normally nothing useful you can do. So it provides a convenient way to just ensure that the resource is cleaned up irrespective of what you're trying to do works or not.

通常处理一次性资源的代码正在以太低的级别工作,无法确定对失败采取的正确措施,因此该异常将留给调用者,后者可以决定要采取什么措施(例如重试,失败,记录等)。
唯一倾向于将 catch 块与可处置资源一起使用的地方是,如果您要翻译异常(即,我认为,您的数据访问层在做什么)。

Typically code that deals with disposable resources is working at too low a level to decide what the correct action is on failure, so the exception is left to propagate to the caller who can decide what action to take (e.g. retry, fail, log, etc.).The only place where you'd tend to use a catch block with a disposable resource is if you're going to translate the exception (which is, I assume, what your data access layer is doing).

这篇关于您如何通过“使用”捕获异常?在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:25