Rya*_*n R 23 c# using-statement try-catch
可能重复:
try/catch + using,正确的语法
我想要try/catch以下内容:
//write to file
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(message);
}
Run Code Online (Sandbox Code Playgroud)
我把这些try/catch块放在using声明中还是周围?或两者?
Jef*_*dge 38
如果您的catch语句需要访问using语句中声明的变量,那么inside是您唯一的选择.
如果您的catch语句在处理之前需要使用中引用的对象,那么inside是您唯一的选择.
如果您的catch语句采取未知持续时间的操作,例如向用户显示消息,并且您希望在此之前处置您的资源,那么外部是您的最佳选择.
每当我有一个与此类似的scenerio时,try-catch块通常采用与使用中调用堆栈相同的不同方法.对于方法来说,知道如何处理在其中发生的异常是不常见的.
所以我的一般推荐是在外面的外面.
private void saveButton_Click(object sender, EventArgs args)
{
try
{
SaveFile(myFile); // The using statement will appear somewhere in here.
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
CD.*_*D.. 13
我想这是首选方式:
try
{
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(message);
}
}
catch(Exception ex)
{
// Handle exception
}
Run Code Online (Sandbox Code Playgroud)
如果你还需要一个try/catch块,那么using语句不会给你带来太大的收益.只是放弃它,而是这样做:
StreamWriter sw = null;
try
{
sw = File.AppendText(filePath);
sw.WriteLine(message);
}
catch(Exception)
{
}
finally
{
if (sw != null)
sw.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36224 次 |
| 最近记录: |