簡體   English   中英

使用streamreader處理異常時遇到麻煩

[英]Trouble with handling exceptions with streamreader

我在StreamReader遇到了麻煩,我有一個設置文件,將設置保存在其中。我想以可以處理異常的方式打開和關閉文件。

當無法加載文件時,我現在想返回false。

我創建了一個為我加載文件的函數:

    private bool LoadSettingsFile(out StreamReader SettingsFile)
    {
        try
        {
            SettingsFile = new StreamReader("Settings.txt");
            return true;
        }
        catch
        {
            //Going to solve the exception later, but if I can't I want to return false.
            SettingsFile = new StreamReader(); //You need to assign StreamReader, but you need to open a file for that.
            //'System.IO.StreamReader' does not contain a constructor that takes 0 arguments
            return false;
        }
    } 

我以這種方式調用該函數:

StreamReader SettingsFile;

if (!LoadSettingsFile(out SettingsFile))
   return false;

如何避免或解決此問題?

如果無法打開文件,為什么要返回StreamReader實例? 您肯定想返回null。 此外,這是從來沒有一個真正的好主意,做一個包羅萬象的在你的異常處理,更具體如

private bool LoadSettingsFile(out StreamReader settingsFile)
{
    try
    {
         settingsFile = new StreamReader("Settings.txt");
         return true;
    }
    catch (IOException) // specifically handle any IOExceptions       
    {
        settingsFile = null;
        return false;
    }
}

可以說這是一種不好的做法,因為通常,.NET代碼比“返回失敗”更喜歡“拋出異常”。 這樣做的原因是,如果您正在“返回失敗”,那么您將依靠代碼的使用者來識別並對此進行處理。 如果引發異常,而代碼的使用者卻忽略了該異常,則應用程序將失敗-通常比使它繼續在未定義狀態下更可取。

在您的情況下,問題在於即使沒有合理的值要分配,您也不得不分配給out參數。 一個明顯的建議是分配null而不是嘗試偽造StreamReader 另外,您可以創建一個空的MemoryStream並為此返回一個讀取器,但是這樣做有些極端,以掩蓋該變量在故障情況下沒有意義並且不應設置的事實。

最終,我建議您允許異常冒泡,而不是返回bool來指示失敗-或者, 返回 StreamReader以獲取成功,並在失敗的情況下返回null

進入Try / Catch塊之前,只需將SettingsFile = null設置為即可。 大概通過返回false可以在更高級別上處理此條件,因此將永遠不會使用SettingsFile。 因此,您的代碼如下所示:

   private bool LoadSettingsFile(out StreamReader SettingsFile) 
    { 
        SettingsFile = null;
        try 
        { 
            SettingsFile = new StreamReader("Settings.txt"); 
            return true; 
        } 
        catch 
        { 
            //Handle Exception Here
            return false; 
        } 
    }  

你可以試試

private StreamReader LoadSettingsFile()
{
    try
    {
        return new StreamReader("Settings.txt");
    }
    catch
    {
        return null;
    }
} 

接着

StreamReader sr = LoadSettingsFile();
if (sr == null) return false;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM