rem*_*rem 4 c# exception-handling exception
如何正确地让异常冒泡?
如果我在调用方法时使用Try-Catch,只是在一个方法中抛出异常而不是试图捕获它?
举例说明:这些方法是否做同样的工作?
例1:
try
{
MyFileHandlingMethod();
}
catch (IOException ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
catch (exception)
{
throw;
}
...
MyFileHandlingMethod()
{
...
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
...
}
Run Code Online (Sandbox Code Playgroud)
例2:
try
{
MyFileHandlingMethod();
}
catch (IOException ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
catch (exception)
{
throw;
}
...
MyFileHandlingMethod()
{
...
try
{
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
}
catch (Exception)
{
throw;
}
...
}
Run Code Online (Sandbox Code Playgroud)
Hen*_*man 12
是的,这两种方法几乎具有相同的效果; rethrowing将展开异常的堆栈 - 意味着堆栈帧"在"下面throw;将被丢弃的方法.它们仍然在堆栈跟踪中,但除非您中断抛出的异常,否则您将无法在调试器中访问它们的本地变量.
像下面那样你没有做任何异常(如日志记录)的catch/throw块是没用的:
catch (Exception)
{
throw;
}
Run Code Online (Sandbox Code Playgroud)
在两个样品中将其移除以进行清理.通常,catch尽可能避免进入区块
并且您的方法有另一个与异常相关的问题,它没有正确释放资源.在tr2.Close();一个在属于finally条款,但它更容易让编译器处理与一个using() {}块:
void MyFileHandlingMethod()
{
...
using (TextReader tr2 = new StreamReader(nfilepath))
{
resultN = tr2.ReadLine();
} //tr2.Dispose() inserted automatically here
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11857 次 |
| 最近记录: |