简体   繁体   English

C#类库异常处理

[英]C# Class Library Exception Handling

Can I do this in ac# class library to handle exceptions that may occur during the execution of a class library code itself? 我可以在ac#类库中执行此操作以处理类库代码本身执行期间可能发生的异常吗? I'm new in writing class libraries and exception handling within it. 我是新编写类库和其中的异常处理的人。 Please advice. 请指教。

private void MethodName(String text)
    {
        try
        {
            ..............
            ..............
            ..............
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }
    }

I've searched in google and stackoverflow, but did not find any article whether I'm allowed to handle exceptions in class libraries this way or if it is not a recommended way to do it. 我在google和stackoverflow中搜索过,但是没有找到任何文章我是否允许以这种方式处理类库中的异常,或者是否不建议这样做。 But it works. 但它的确有效。 May be a dumb question, but I have this doubt. 可能是一个愚蠢的问题,但我有这个疑问。

Thanks. 谢谢。

Yes you can do that, but in general you should only catch exceptions if you are going to do something with it - ie swallow it or add value to it (by transforming, wrapping or logging it). 是的,你可以这样做,但一般来说,你应该只捕获例外,如果你要用它做一些事情 - 即吞下它或为它增加价值(通过变换,包装或记录它)。

Using your example method, you should throw an exception if text is null and your method expects a value. 使用您的示例方法,如果text为null并且您的方法需要一个值,则应该引发异常。 Other than that you should let exceptions bubble out for the caller to handle unless you are going to do something with it, or it is an expected exception that you intend to suppress. 除此之外,你应该让异常冒出来让调用者处理,除非你打算对它做一些事情,否则它是你打算压制的预期异常。

You also shouldn't throw a new exception, instead just use the throw keyword to rethrow the current exception: 您也不应引发新的异常,而只需使用throw关键字重新引发当前异常:

catch (Exception ex)
{
    //do something

    throw;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM