从 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/