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
}
的
第二个catch是可选的,当然。
The second catch is optional, of course.
这篇关于C#中的try-catch-ELSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!