简体   繁体   English

使用streamreader处理异常时遇到麻烦

[英]Trouble with handling exceptions with streamreader

I'm having some trouble with StreamReader , I have a settings file where I save settings in. I want to open and close the file on a way that I also can handle exceptions. 我在StreamReader遇到了麻烦,我有一个设置文件,将设置保存在其中。我想以可以处理异常的方式打开和关闭文件。

When the file can't be loaded I want to return for now false. 当无法加载文件时,我现在想返回false。

I created a function that loads the file for me: 我创建了一个为我加载文件的函数:

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

I call the function on this way: 我以这种方式调用该函数:

StreamReader SettingsFile;

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

How can I avoid or solve this? 如何避免或解决此问题?

If you are unable to open the file, why would you want to return a StreamReader instance? 如果无法打开文件,为什么要返回StreamReader实例? Surely you would want to return null. 您肯定想返回null。 Also, it's never really a good idea to do a catch-all in your exception handling, be more specific eg 此外,这是从来没有一个真正的好主意,做一个包罗万象的在你的异常处理,更具体如

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

This is arguably bad practise in that, in general, .NET code prefers "throwing exceptions" over "returning failure." 可以说这是一种不好的做法,因为通常,.NET代码比“返回失败”更喜欢“抛出异常”。 The reason for this is that, if you are "returning failure," you rely on the consumer of your code to recognise this and do something about it. 这样做的原因是,如果您正在“返回失败”,那么您将依靠代码的使用者来识别并对此进行处理。 If you throw an exception and the consumer of your code ignores it, the application will fail - which is often more desireable than for it to continue in an undefined state. 如果引发异常,而代码的使用者却忽略了该异常,则应用程序将失败-通常比使它继续在未定义状态下更可取。

In your case, the problem is that you're forced to assign to your out parameter even when there is no sensible value to assign there. 在您的情况下,问题在于即使没有合理的值要分配,您也不得不分配给out参数。 One obvious suggestion is to assign null instead of trying to fake a StreamReader . 一个明显的建议是分配null而不是尝试伪造StreamReader Alternatively, you could create an empty MemoryStream and return a reader for that, but this is going to some extreme lengths to cover up the fact that the variable has no meaning in a failure case and should not be set. 另外,您可以创建一个空的MemoryStream并为此返回一个读取器,但是这样做有些极端,以掩盖该变量在故障情况下没有意义并且不应设置的事实。

Ultimately I'd suggest you allow the exception to bubble rather than returning a bool to indicate failure - or alternatively, return the StreamReader for success and return null in the case of failure. 最终,我建议您允许异常冒泡,而不是返回bool来指示失败-或者, 返回 StreamReader以获取成功,并在失败的情况下返回null

Just set SettingsFile = null before entering into the Try/Catch block. 进入Try / Catch块之前,只需将SettingsFile = null设置为即可。 Presumably by returning false you're handling this condition at a higher level, so SettingsFile will never be used. 大概通过返回false可以在更高级别上处理此条件,因此将永远不会使用SettingsFile。 So your code would look like this: 因此,您的代码如下所示:

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

You can try 你可以试试

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

and then 接着

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM