C#try-catch-else [英] C# try-catch-else
问题描述
从Python到C#的异常处理有一件事情是,在C#中,似乎没有任何方式指定一个else子句。例如,在Python中,我可以写这样的东西(注意,这只是一个例子,我不是问什么是最好的方式来阅读文件):
One thing that has bugged me with exception handling coming from Python to C# is that in C# there doesn't appear to be any way of specifying an else clause. For example, in Python I could write something like this (Note, this is just an example. I'm not asking what is the best way to read a file):
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#代码看,人们只会写下列内容:
From what I have seen in most C# code people would just write the following:
try
{
reader = new StreamReader(path);
string line = reader.ReadLine();
char character = line[30];
}
catch (Exception)
{
// Uh oh something went wrong, but where?
}
这样做的麻烦是我不想超出范围这是因为文件中的第一行不能包含超过30个字符的事实。我只想捕获与文件流的读取有关的异常。有没有类似的构造可以在C#中使用来实现同样的事情?
The trouble with this is that I don't want to catch out of range exception coming from the fact that the first line in the file may not contain more than 30 characters. I only want to catch exceptions relating to the reading of the file stream. Is there any similar construct I can use in C# to achieve the same thing?
推荐答案
捕获特定类别的异常
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.
}
当然,第二个catch是可选的。因为你不知道发生了什么,吞咽这个最一般的例外是非常危险的。
The second catch is optional, of course. And since you don't know what happened, swallowing this most general exception is very dangerous.
这篇关于C#try-catch-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!