2012-03-08 119 views
1

是否有可能返回一個布爾值,並在同一個方法中重新拋出異常?我試着用下面的代碼,它一直說不可檢測的代碼被檢測到或者我不能退出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(); 
     } 
    } 
} 

回答

4

一旦拋出一個異常,當前方法中的處理就結束了,並且異常處理調用堆棧。要麼在本地處理你的異常,然後返回你的布爾值,要麼拋出它們,讓它們在前端處理它們並處理它們。

+0

非常感謝。 – 2012-03-08 12:18:22

相關問題