加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我们可以在c#中创建一个异常类,它可以推断出异常的类型并相应地

发布时间:2020-12-16 01:59:28 所属栏目:百科 来源:网络整理
导读:我听说过,我们需要在代码时间知道我们要面对的例外情况并提供必要的捕获量. 现在我们不能推断刚从Exception类发生的实际异常的类型,然后转换它并获得所需的信息? 例如考虑这个: private void button1_Click(object sender,EventArgs e) { try { //try doin
我听说过,我们需要在代码时间知道我们要面对的例外情况并提供必要的捕获量.

现在我们不能推断刚从Exception类发生的实际异常的类型,然后转换它并获得所需的信息?
例如考虑这个:

private void button1_Click(object sender,EventArgs e)
        {
            try
            {
                //try doing something to generate and exception
                int blah =8 / Convert.ToInt32(txtBox.Text);
            }
            catch (Exception ex)
            {
                //ex.GetType().Name
                //getting the type and casting it according to the retrieved name
                //and finally showing the more detailed info of the occurred exception
               //for example like this?
               //MessageBox((ex.GetType())ex).Message);  
            }
        }

这只是传达我意义的一个示例,假设如果可能的话,我们将这个自定义类继承自Exception并为此目的进行所需的工作.

我们不能这样做吗?如果我们能怎样才能施展它?如果不能这样做,为什么呢?

解决方法

如果需要,可以将异常处理逻辑委托给一些定义良好的模块,其目的是…处理异常:)也许这样……?

try {
    // code that throws something
} catch (Exception e) {
    myExceptionHandlingStrategy.handleException(e);
}

其中myExceptionHandlingStrategy是MyExceptionHandlingStrategy的一个实例,MyExceptionHandlingStrategy是一个暴露接口IExceptionHandlingStrategy的模块,定义(可能)如下:

interface IExceptionHandlingStrategy {
    void handleException(Exception e);
}

然后,在该接口的某些实现中(您可能有很多),您可以自由地执行以下操作:

if (e is SomethingBadException) {
    // show some message
} else if (e is SomeOtherKindOfException) {
    // do something else instead
} else {
    throw new CannotHandleThisException(e);
}

PS:没有反思:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读