C# try-catch-else

标签 c# exception-handling

从 Python 到 C# 的异常处理一直困扰着我的一件事是,在 C# 中似乎没有任何指定 else 子句的方法。例如,在 Python 中我可以写这样的东西(注意,这只是一个例子。我不是在问什么是读取文件的最佳方式):

try
{
    reader = new StreamReader(path);
}
catch (Exception)
{
    // Uh oh something went wrong with opening the file for reading
}
else
{
    string line = reader.ReadLine();
    char character = line[30];
}

根据我在大多数 C# 代码中看到的情况,人们只会编写以下内容:

try
{
    reader = new StreamReader(path);
    string line = reader.ReadLine();
    char character = line[30];
}
catch (Exception)
{
    // Uh oh something went wrong, but where?
}

问题在于我不想捕获由于文件中的第一行可能不包含超过 30 个字符这一事实而引起的超出范围的异常。我只想捕获与读取文件流有关的异常。我可以在 C# 中使用任何类似的构造来实现相同的目的吗?

最佳答案

捕获特定类的异常

try
{
    reader = new StreamReader(path);
    string line = reader.ReadLine();
    char character = line[30];
}
catch (IOException ex)
{
    // Uh oh something went wrong with I/O
}
catch (Exception ex)
{
    // Uh oh something else went wrong
    throw; // unless you're very sure what you're doing here.
}

当然,第二个捕获是可选的。并且由于您不知道发生了什么,吞下这个最普遍的异常是非常危险的。

关于C# try-catch-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1177438/

相关文章:

c# - 正则表达式匹配动态模式

c# - 音频从输入到扬声器的硬件直通 - 不是在软件中完成

c# - AutoResetEvent 设置后立即复位

Java - 在 try/catch 中执行 try/catch 是不好的做法吗?

java - 为我的应用程序的所有线程定义一个全局 UncaughtExceptionHandler

java - Spring 。异常翻译如何工作?

c# - Json.NET 反序列化为带引用的动态对象

c# - Linq to Sql 中的子查询

ruby - 如何检测API错误?

.net - 错误记录例程中的异常怎么办?