捕获一般例外 [英] Catching general exceptions

查看:146
本文介绍了捕获一般例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 >,你不应该赶上一般例外。我敢肯定有处理,一个计算器问题,我明白为什么这不是一个很好的做法,但我只是看到了的另一个MSDN文章今天:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}



是否有任何理由要追赶在这个例子中一种普遍的例外或只是他们是懒得写一个例子捕获所有特定异常?

Is there any justification to catching a general exception in that example or is it just that they were lazy to write an example catching all the specific exceptions?

推荐答案

在这种情况下,这是一个的例如的并且是一个可怜的,喜欢的许多的MSDN上的代码示例。

In this case, this is an example and is a poor one at that, like many code examples on MSDN.

这应该是醒目的IO异常,而不是基类。

This should be catching an IO Exception instead of the base class.

这将使感赶上唯一的地方例外是在记录一个全球性的异常处理程序,只要你重新抛出。

The only place it would make sense to catch Exception is in a global exception handler for logging, provided you rethrow.

这篇关于捕获一般例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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