如何捕获异常 [英] How to catch exceptions

查看:275
本文介绍了如何捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一个正确处理异常的应用程序。这是一个WCF服务。之前所有其他的都是简单的应用程序只是为了自己我对C#中的异常处理知识很少。



我有一个这样的代码:

  MembershipUser memUser = Membership.GetUser(username); 

DatabaseDataContext context = new DatabaseDataContext();
UserMembership user = UserMembership.getUserMembership(memUser);
ItemsForUser itemUser = Helper.createItemForUser(ref item,memUser);
Helper.setItemCreationInfo(ref item,user);
context.Items.InsertOnSubmit(item);
context.SubmitChanges();

在此代码中,可能会发生一些例外。像NullReferenceException一样。我如何知道哪个对象引起异常,所以我可以知道在catch中做什么以及返回给客户端的内容?

解决方案

一般来说,你不应该抓住任何例外。



我知道这听起来很奇怪,但事实上你应该只能捕捉到你可以实际做某些事情的异常,而且通常也不能对异常做任何事情。



此规则的异常与处理异常的含义有关。在某些应用程序中,处理异常意味着要记录它。在其他(例如ASP.NET)中,最好不要处理异常,因为框架(在这种情况下为ASP.NET运行状况监视)将为您记录。



在事件驱动的代码,如Windows窗体中,我发现有必要捕获事件处理程序中的异常。至少在.NET的早期版本中,允许异常传播到例如按钮点击事件之外产生不愉快的结果。我通常会捕获异常并将其显示在对话框中。



在多层应用程序中,可能会在层级边界捕获异常,然后重新创建一个新的,具体例外:

  try 
{
// ...
}
catch(Exception ex)
{
throw new TierException(Some message,ex);
}

另一个用例是捕获异常,然后再添加一个新的异常其中的信息:

  public int GetValueFromConfigurationFile(...)
{
const string configFileName = ......;
try
{
// ...
}
catch(FileNotFoundException fEx)
{
throw new InvalidOperationException(
String.Format(找不到配置文件{0},configFileName),
fEx);
}
}

在这种情况下,您正在捕获一个特定的异常 FileNotFoundException ),并提供您无法知道的来电者信息:找不到该文件是一个配置文件。



一般消息是:
- 只捕获你知道如何处理
的异常 - 捕获最具体的异常可能
- 创建新异常时始终包含内部异常,以保留异常链
- 要重新抛出当前异常,请使用 throw; ,而不是 throw ex; p>

还有一些,我将尝试从Microsoft框架设计指南中找到您的参考。



PS如果有人可以找到这个重复的问题,请随意关闭重复。我不介意失去任何代表。我只是找不到重复的。






我应该刚刚发布了链接到异常处理一个href =https://stackoverflow.com/tags/exception-handling/info>标签wiki ,其中说:


但是,对于.NET程序上下文中的异常处理,请参阅

异常的设计指南



This is my first application that will deal with exceptions properly. It's a WCF service. All the other before were simple apps just for myself. I have very small knowledge about exception handling in C#.

I have a code like this:

MembershipUser memUser = Membership.GetUser(username);

DatabaseDataContext context = new DatabaseDataContext();
UserMembership user = UserMembership.getUserMembership(memUser);
ItemsForUser itemUser = Helper.createItemForUser(ref item, memUser);
Helper.setItemCreationInfo(ref item, user);
context.Items.InsertOnSubmit(item);
context.SubmitChanges();

In this code a few exceptions can happen. Like NullReferenceException for example. How do I know which object caused the exception so I can know what to do in the catch and what to return to the client?

解决方案

In general, you should not catch any exceptions.

I know this sounds strange, but the fact is that you should only catch exceptions you can actually do something about, and you usually can't do anything about exceptions.

The "exceptions" to this rule have to do with what it means to "handle" an exception. In some applications, "handling" the exception means to log it. In others (ASP.NET, for instance), it's better to not handle the exception, because the framework (ASP.NET Health Monitoring in this case) will log it for you.

In event-driven code, like Windows Forms, I find it's necessary to catch exceptions within event handlers. At least in earlier versions of .NET, allowing the exception to propagate outside of, for instance, a button click event produced unpleasant results. I typically catch the exception and display it in a dialog box.

In a multi-tier application, one might catch exceptions on tier boundaries, then rethrow a new, tier-specific exception:

try
{
   // ...
}
catch (Exception ex)
{
    throw new TierException("Some message", ex);
}

Another use case is to catch the exception, then throw a new exception with more information in it:

public int GetValueFromConfigurationFile(...)
{
    const string configFileName = "...";
    try
    {
        // ...
    }
    catch (FileNotFoundException fEx)
    {
        throw new InvalidOperationException(
            String.Format("Can't find configuration file {0}", configFileName), 
            fEx);
    }
}

In this case, you are catching a specific exception (FileNotFoundException), and providing your caller information they could not otherwise know: that the file not found was a configuration file.

The general message is: - Only catch exceptions you know how to handle - Catch the most specific exception possible - Always include the inner exception when creating a new exception, to preserve the chain of exceptions - To rethrow the current exception, use throw;, not throw ex;

There are a few more, and I'll try to find you the reference from the Microsoft Framework Design Guidelines.

P.S. If someone can find the question this is a duplicate of, feel free to close as a duplicate. I don't mind losing any rep from this. I just couldn't find the duplicate.


I should have just posted the link to the "exception-handling" tag wiki, where it says:

However, for exception handling in the context of .NET programs, see "Design Guidelines for Exceptions".

这篇关于如何捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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