Mar*_*urn 31 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];
}
Run Code Online (Sandbox Code Playgroud)
从我在大多数C#代码中看到的,人们只会写下面的内容:
try
{
reader = new StreamReader(path);
string line = reader.ReadLine();
char character = line[30];
}
catch (Exception)
{
// Uh oh something went wrong, but where?
}
Run Code Online (Sandbox Code Playgroud)
这样做的问题在于我不希望因为文件中的第一行不能包含超过30个字符而超出范围异常.我只想捕获与读取文件流有关的异常.我可以在C#中使用任何类似的构造来实现相同的功能吗?
Hen*_*man 46
捕获特定类别的异常
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.
}
Run Code Online (Sandbox Code Playgroud)
当然,第二个捕获是可选的.而且由于你不知道发生了什么,吞下这个最普遍的例外是非常危险的.
Joh*_*bom 12
你可以这样写:
bool success = false;
try {
reader = new StreamReader(path);
success = true;
}
catch(Exception) {
// Uh oh something went wrong with opening the file for reading
}
finally {
if(success) {
string line = reader.ReadLine();
char character = line[30];
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
try
{
reader = new StreamReader(path);
}
catch (Exception)
{
// Uh oh something went wrong with opening the file for reading
}
string line = reader.ReadLine();
char character = line[30];
Run Code Online (Sandbox Code Playgroud)
但是,当然,您必须设置reader正确的状态或return方法.
捕获更具体的例外情况.
try {
reader = new StreamReader(path);
string line = reader.ReadLine();
char character = line[30];
}
catch(FileNotFoundException e) {
// thrown by StreamReader constructor
}
catch(DirectoryNotFoundException e) {
// thrown by StreamReader constructor
}
catch(IOException e) {
// some other fatal IO error occured
}
Run Code Online (Sandbox Code Playgroud)
此外,通常,尽可能处理最具体的异常并避免处理基础System.Exception.