C# 返回bool并重新引发异常
是否可以在同一方法中返回bool并重新引发异常?我尝试了下面的代码,它一直说检测到无法访问的代码,或者我无法退出finally块C# 返回bool并重新引发异常,c#,c#-4.0,exception-handling,C#,C# 4.0,Exception Handling,是否可以在同一方法中返回bool并重新引发异常?我尝试了下面的代码,它一直说检测到无法访问的代码,或者我无法退出finally块 public bool AccessToFile(string filePath) { FileStream source = null; try { source = File.OpenRead(filePath); source.Close(); return true; }
public bool AccessToFile(string filePath)
{
FileStream source = null;
try
{
source = File.OpenRead(filePath);
source.Close();
return true;
}
catch (UnauthorizedAccessException e)
{
string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
unAuthorizedStatus += e.Message;
MessageBox.Show(unAuthorizedStatus, "Error Message:");
throw;
}
catch (Exception e)
{
string generalStatus = null;
if (filePath == null)
{
generalStatus = "General error: \n\r";
}
else
{
generalStatus = filePath + " failed. \n\r";
generalStatus += e.Message;
}
MessageBox.Show(generalStatus, "Error Message:");
throw;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
一旦抛出异常,当前方法中的处理将完成,异常将进入调用堆栈。要么本地处理异常,然后返回布尔值,要么抛出异常,让它们冒泡起来,并在前端处理它们。一旦抛出异常,当前方法中的处理将完成,异常将在调用堆栈中运行。要么本地处理异常,然后返回布尔值,要么抛出异常,让异常冒泡起来,在前端处理异常