Eri*_*tas 4 .net c# finally try-catch
如果我使用try/catch/finally块我应该在哪里以及如何初始化变量?例如,假设我正在尝试使用FileStream.我想捕获创建或使用流时抛出的任何异常.然后,无论是否有任何问题,我都希望确保创建的任何流都已关闭.
所以我会做这样的事情:
System.IO.FileStream fs;
try
{
fs = new System.IO.FileStream("C:\test.txt", System.IO.FileMode.Open);
//do something with the file stream
}
catch (Exception exp)
{
//handle exceptions
}
finally
{
//ERROR: "unassigned local variable fs"
if (fs != null)
{
fs.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这给了我在finally块中说错误unassigned local variable fs.然而,如果我改变的声明fs,以System.IO.FileStream fs = null它的工作原理.
为什么我需要显式设置fs为null?我也试过fs在try块中声明,但后来我The name fs does not exsist in the current context在finally块中得到了错误.
BTW:我知道我可以使用Using块,但我的问题是要了解try/catch/finally块的正确用法.
小智 5
分配fs = null;
System.IO.FileStream fs = null;
try
{
fs = new System.IO.FileStream("C:\test.txt", System.IO.FileMode.Open);
//do something with the file stream
}
catch (Exception exp)
{
//handle exceptions
}
finally
{
//ERROR: "unassigned local variable fs"
if (fs != null)
{
fs.Close();
}
}
Run Code Online (Sandbox Code Playgroud)