Skip to main content
 首页 » 编程设计

c#之返回 bool 值并重新抛出异常

2024年02月23日19Free-Thinker

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

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

请您参考如下方法:

一旦抛出异常,当前方法中的处理就会结束,并且异常会进入调用堆栈。要么在本地处理您的异常,然后返回您的 bool 值,要么抛出它们,让它们冒泡并在前端处理它们。