【发布时间】:2014-05-13 15:33:27
【问题描述】:
我对编程相当陌生,我想知道构建错误处理的正确方法是什么。我已经搜索了互联网,但我没有找到关于所有 try/catch/finally 语句的结构以及它们如何相互交互的可靠信息。
我想提出我的想法,我认为我应该如何在代码中构建我的错误处理,我想邀请大家检查这是否正确。一个很大的好处是通过其他一些研究来支持它,这是某种常见的做法。
所以我这样做的方法是在几乎所有地方都放置 try 语句! (我希望我这样说没有激怒所有人)。 PS - 我也了解捕获不同类型的异常,我只是为了解释目的而捕获类型“异常”。
例如:
我在普通控制台应用程序中从 Main 开始,然后创建一个 A的实例。
然后我在其上调用一个名为 AMethod1 (a.AMethod1) 的成员函数。
A.AMethod1 创建类 B 的实例,然后调用 BMethod1 (b.BMethod1)。
这就是我将如何处理错误:
public class Program
{
static void Main (string[] args)
{
//I do not place simple code like below inside the try statement,
//because it is unnecessary and will slow the process down.
//Is this correct?
const int importantNumber = 45;
string name;
IRepositoryFactory repoFactory;
A a;
//And then I put code in 'try' where I feel it may go wrong.
try
{
a = new A();
a.AMethod1();
//Some other code
}
catch (Exception ex)
{
HandleError(ex);
}
}
}
// End of scope of Program! The functions below belong to their relative
// classes.
public void AMethod1()
{
try
{
B b = new B();
b.BMethod1();
}
catch (Exception ex)
{
//Preserving the original exception and giving more detailed feedback.
//Is this correct?
//Alternative - you still could do a normal 'throw' like in BMethod1.
throw new Exception("Something failed", ex);
}
}
public void BMethod1()
{
try
{
//some code
}
catch (Exception ex)
{
throw; //So I don't lose stack trace - Is this correct?
}
}
总结:
- 我把所有代码都放在了 try 语句中(除了 以上代码)
- 在客户端级别(在调用堆栈的开头)我 捕捉错误并处理它。
- 向下调用堆栈,我只是 抛出异常,这样我就不会破坏堆栈信息。
我非常感谢一些资源,这些资源解释了程序员是如何构建他们的错误处理的。请不要忘记阅读代码中的 cmets。
【问题讨论】:
-
catch块不是免费的。如果你想对它们做一些有用的事情(例如在重新抛出它们之前记录它们),你应该只捕获异常。否则,就让它们传播给调用者。 -
这对codereview.stackexchange.com来说似乎是个好问题
-
throw;适合重新抛出,throw new Exception(....)适合添加更多信息和重新抛出。您唯一不想做的是throw ex;,它会清除堆栈跟踪。
标签: c# exception-handling structure