关于c#中异常的问题 [英] a question about exception in c#

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

问题描述

以下是代码段:

class xxx
{

  public xxx(){}

  try
  {
    throw new Exception(InvalidoperationException);
  }
  catch(Exception x)
  {
  }
  catch(InvalidoperationException x)
  {
  }
}

任何人都可以告诉这里提出哪个异常,其背后的原因是什么。

can anyone tell which exception will raise here and what is the reason behind it.

推荐答案

哇,这里有很多问题。从哪里开始?

Wow, lots of problems here. Where to start?


  1. 该代码将无法编译。您定义的 try-catch 块不在任何方法之外,不允许。您需要将其移动到方法的之内。

  1. That code won't compile. The try-catch block that you've defined is outside of any method, which is not allowed. You need to move it inside of a method.

不要在方法中抛出一个方法来打扰自己。这通常被称为使用流量控制的异常,这是不鼓励的。与执行此操作相关的性能成本,并且它也使得监视在使用调试器时抛出异常的异常非常混乱,当您有代码抛出并捕获它自己的异常时。如果需要,使用布尔变量(称为标志)进行流量控制。

Never throw a method that you intend to catch yourself later in the method. That's commonly known as using exceptions for "flow control", which is roundly discouraged. There is a performance cost associated with doing so, and it also makes it very confusing to monitor the exceptions that are being thrown when using a debugger when you have code that's throwing and catching it's own exceptions. Use boolean variables (known as flags) for flow control, if necessary.

首先捕获最常见的衍生异常类。这意味着您应该首先抓住 InvalidOperationException ,然后再尝试抓住异常。您需要在您所拥有的代码中扭转您的 catch 块的顺序。

Always catch the most derived exception class first. That means you should catch InvalidOperationException first, before trying to catch Exception. You need to reverse the order of your catch blocks in the code that you have.

实际从不 catch System.Exception 。你应该捕捉的唯一例外是您明确明白并能够处理的例外。几乎没有办法知道发生了什么错误或如何处理它,只有您所拥有的信息是泛型异常被抛出。

You should practically never catch System.Exception. The only exceptions that you should catch are those that you explicitly understand and are going to be able to handle. There's virtually no way that you're going to know what went wrong or how to handle it when the only information you have is that a generic exception was thrown.

沿着这些相同的行,你也应该永远不会从你自己的代码抛出这个异常。选择一个更具描述性的异常类,它从基础 System.Exception 继承,或通过继承自己创建自己的异常类。

Along those same lines, you also should never throw this exception from your own code. Choose a more descriptive exception class that inherits from the base System.Exception class, or create your own by inheriting from the same.



我看到其他答案正在向您展示您的代码应该如何的示例代码,是吗被重写我不会这样做,因为如果我重写你的代码是正确的,我最终会这样:


I see that other answers are showing you sample code of what your code should look like, were it to be rewritten. I'm not going to do that because if I rewrote your code to be correct, I'd end up with this:

class Xxx
{
    public Xxx()
    {

    }
}

不是特别有用。

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

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