有没有一个普通的Exception类,除了消息之外还需要一个int? [英] Is there a general Exception-class that takes an int besides the message?

查看:120
本文介绍了有没有一个普通的Exception类,除了消息之外还需要一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个异常类,它同时包含消息和 int 作为参数,而宁愿使用现在的一个,而不是创建我自己的自定义派生异常。

I need an Exception class that takes both a message and an int as parameters, and would rather use an existing one instead of creating my own custom derived Exception.

我一直在寻找一个,但这比我想象的更加困难。

I've been searching for one, but it's proving more difficult than I thought.

有没有这样的(一般命名的)类?

Is there such a (generally named) class?

编辑

我打算抓住它并显示:Error+ ex.Message + ex.Code.ToString();

I intend to catch it and display: "Error " + ex.Message + ex.Code.ToString();.

错误代码是一个消息,我不想向用户显示。 (调试技术等)。 将显示错误 ,以便用户可以告诉我他有什么代码。)

The error-code is for a message that I would rather not display to a user. (Technical stuff for debugging etc. The error code will be displayed so the user can tell me what code he got.)

我喜欢现有异常的原因是我想在我的所有应用程序中都有统一的处理异常的方式,而不必每次都要定义它们。

My reason for preferring an existing Exception is that I want to have a uniform way of handling exceptions in all of my applications and not have to define them every time.

推荐答案

如前所述,最好的事情是为您的应用程序域创建一个或多个特殊的异常类。一个很好的设计还包括优雅地分解的条款。

The best thing, as already noted, is to create 1 or more special Exception classes for your Application Domain. A good design also includes provisions to break down gracefully.

但是还有一条路线,很少使用 数据属性

But there is another route, the seldom used Data property of the base Exception class.

它是一个字典,允许您向任何异常添加自定义数据。拦截(捕获和重新抛出)异常并且想要添加一些环境信息时很有用。

It is a Dictionary that allows you to add custom data to any exception. Useful when you intercept (catch and re-throw) exceptions and want to add some ambient information.

try 
{
    using (var reader = File.OpenText(fileName))
    { 
       ... 
    }
}
catch(Exception e)
{
   e.Data.Add("Filename", fileName);
   throw;
}

这篇关于有没有一个普通的Exception类,除了消息之外还需要一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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