试图了解在C#中的异常 [英] Trying to understand exceptions in C#

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

问题描述

我真的不使用我的code以往任何的try /渔获量,但我想打破这个习惯,现在获得在使用异常。

I do not really use any try/catches in my code ever but I'm trying to break that habit and now get in to using exceptions.

我想有它在我的应用程序会读取一个文件,我想现在落实,最重要的地方,但我不能确定的最佳实践的这样做。目前我正在做这样的事情:

I figure the most important place to have it in my application would be reading a file and I'm trying to implement that now but I'm unsure of the "best-practices" for doing so. Currently I'm doing something like this:

private void Parse(XDocument xReader)
{
    IEnumerable<XElement> person = xReader.Descendants("Person").Elements();

    foreach (XElement e in person)
        personDic[e.Name.ToString()] = e.Value;

    if (personDic["Name"] == null || personDic["Job"] == null || personDic["HairColor"] == null)
        throw new KeyNotFoundException("Person element not found.");
}

但我不能确定这是否是正确的。我有这样处理的:

But I am unsure if this is correct. I have this for handling it:

try
{
    personsReader.Read(filename, persons);
}
catch (KeyNotFoundException e)
{
    MessageBox.Show(e.Message);

    return;
}

// Do stuff after reading in the file..

不过显示e.Message时,它只是显示了通用KeyNotFoundException错误信息,而不是通过自定义错误消息。此外,我不知道,如果在一般的,我要对这个整个异常处理的东西正常。我回来在catch,因为如果该文件未成功读取很明显,我只想pretend喜欢的用户从来没有试图打开一个文件,并让他与另一个文件再试一次。

However when showing e.Message it just shows the generic KeyNotFoundException error message and not by custom error message. Also I'm not sure if in general I am going about this whole "exception handling stuff" properly. I do return in the catch because if the file is not read successfully obviously I just want to pretend like the user never tried to open a file and let him try again with another file.

我这样做是否正确?再次我是相当新的使用异常,我想让它肯定我继续,并应用该到我的程序的其他部分之前走对路了。

Am I doing this properly? Again I am fairly new to using exceptions and I want to make it sure I got it down right before continuing on and applying this to the rest of my program.

另外,为什么人们说不做赶上(例外五)?这似乎是在这种情况下,我想这样做,因为无论在文件中读取时出现了什么错误,如果有错误的,我想停止读取文件,显示错误信息,并返回。这难道不总是如此?我能理解不想处理例外五,如果你想处理一些不同的基础上,异常,但在这种情况下就不是我想只是在处理任何情况下的基本异常类出了问题?

Also, why do people say not to do catch (Exception e)? It seems like in this case I would want to do that because regardless of what error occurs when reading in a file, if there is an error, I want to stop reading the file, display the error message, and return. Wouldn't that always be the case? I can understand not wanting to handle Exception e if you would want to handle something differently based on the exception but in this case wouldn't I want to just handle the base exception class in case anything goes wrong?

推荐答案

您应该捕获异常时,你可以的处理的条件下,做一些有用的东西。否则,你应该让它泡了调用堆栈,也许上面有人,你可以处理它。有些应用程序有未处理的异常处理程序的最外层,但总体来处理它,除非你知道你有一些有用的方法来处理它,让它去。

You should catch exceptions when you can handle the condition and do something useful. Otherwise you should let it bubble up the call stack and perhaps someone above you can handle it. Some apps have unhandled exception handlers to handle it at the outer most layer but in general, unless you know you have some useful way to handle it, let it go.

在你的情况,你处理不能够阅读资源,并通知用户。你处​​理吧。关于一般例外,有一件事你可以做的是捕获并重新抛出一个更好的异常。如果你这样做,一定要incude的根本原因异常作为内部异常。您也可以跟踪,或者相应的日志的详细信息。

In your case, you're handling not being able to read a resource and informing the user. You're handling it. Concerning the generic exception, one thing you can do is catch and re-throw a better exception. If you do that, make sure you incude the root cause exception as the inner exception. You can also trace or log the details if appropriate.

throw new MyGoodExceptionType ("Could not read file", e);  // e is caught inner root cause.

现在的UI显示出良好的错误,也许是内心根本原因是在日志等等...

Now the UI shows a good error and perhaps the inner root cause is in a log etc...

一些典型的错误:

  • 处理异常深藏在堆栈中一个通用库的方法:请记住,一个共同的库函数可以被调用,在许多不同的code路径。你可能没有上下文是否应该处理以及是否是合适的处理。呼叫者在堆栈较高可能有上下文并知道它是否是安全的处理。通常,这意味着code高层决定如何处理。在下层,一般你让他们流过。

  • Handling exceptions deep in the stack in a generic library method: Remember that a common library function may get called in many different code paths. You likely don't have the context whether it should be handled and whether it's appropriate to handle it. the caller higher in the stack likely has context and knows whether it's safe to handle. Typically that means higher layers of code decide to handle. In lower layers, typically you let them flow.

吞咽异常:有些code捕获的异常(在堆栈特别是低),然后在根的条件只是蒸发,使其郁闷了调试。一旦阿甘,如果你能处理它,这样做。如果不能,让他走了。

Swallowing Exception: Some code catches exceptions (especially lower in the stack) and then the root condition just evaporates making it maddening to debug. Once agan, if you can handle it, do so. If not, let it go.

异常应该是例外:不要使用excpetions进行流量控制。例如,如果你正在阅读的资源,不要试图读取,然后捕获异常,并作出决策点。相反,呼叫ifexists,查布尔和你code作出决定。当你设置调试器打破这种异常有助于特别。您应该能够运行干净,如果调试器中断,它应该是一个真正的问题。有了不断的调试时,调试器休息是有问题的。我个人比较喜欢抛出异常很少,总是尽量避免进行流量控制。

Exceptions should be exceptional: Don't use excpetions for flow control. For example, if you're reading a resource, don't try and read and then catch the exception and make a decision point. Instead, call ifexists, check bool and make decisions in your code. this especially helps when you set the debugger to break on exceptions. You should be able to run clean and if the debugger breaks, it should be a real issue. Having the debugger break constantly when debugging is problematic. I personally like throwing exceptions very rarely and always try to avoid for flow control.

希望有所帮助。

这篇关于试图了解在C#中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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