Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回bool并重新引发异常_C#_C# 4.0_Exception Handling - Fatal编程技术网

C# 返回bool并重新引发异常

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; }

是否可以在同一方法中返回bool并重新引发异常?我尝试了下面的代码,它一直说检测到无法访问的代码,或者我无法退出finally块

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();
        }
    }
}

一旦抛出异常,当前方法中的处理将完成,异常将进入调用堆栈。要么本地处理异常,然后返回布尔值,要么抛出异常,让它们冒泡起来,并在前端处理它们。

一旦抛出异常,当前方法中的处理将完成,异常将在调用堆栈中运行。要么本地处理异常,然后返回布尔值,要么抛出异常,让异常冒泡起来,在前端处理异常