应用程序错误处理 - 最佳实践

问题描述:

我想做一个普通的调查,询问这里的成员认为最好的方法是提高和处理错误和例外。



方法1:抛出例外

I'd like make a general survey asking what members here think is best way(s) to Raise and Handle Errors and Exceptions.

Method 1: throw Exceptions

string method1()
{
if(notSuccessful)
throw new Exception("reason");

//or
try{

}
catch(Exception e)
{
	throw e;
}
}





方法2:返回null或空对象





Method 2: return null or empty object

MyObject method2()
{
MyObject obj = null;

if(success){
obj=new MyObject();
}

return obj;
}





方法3:返回bool或int并保存对象数据



Method 3: return bool or int and save object data

private myObject; //class variable

public GetMyObject(){return this.myObject;}

bool method3(){

this.myObject = null;

if(success){
this.myObject=new MyObject();
}

return success;
}





方法4:HasError和GetLastError





Method 4: HasError and GetLastError

public bool HasErrors
{
	get { return this.hasErrors; }
}

public string LastError
{
	get { return this.lastError; }
}





您认为最佳方法是什么?



What do you think is best approach?

所有错误,没有任何排除。这是结构异常处理的目的,以避免这种情况。



也许,只有第一个案例值得一些评论。这个代码在逻辑上等同于根本不处理异常,但实际上它是浪费的:它只是花费一些额外的资源,包括开发和支持那些多余的行,没有别的。应该仅为特定目的重新抛出异常:在某些时候,异常类型或某些条件下创建选择性处理。在这种情况下,一些条件情况在本地处理,有些被重新抛出堆栈(你知道堆栈操作吗?这是关键),要在其他地方处理。此外,重要的是不要在本地处理异常。该机制最重要的目的之一是最大限度地减少处理并将正常执行流与异常分开。因此,在代码的大多数地方,异常应该继续向上传播,这是通过不处理异常来实现的。



那么,该怎么办?首先,您需要对异常如何工作有一些基本的了解。这是一种基于调用堆栈绕过正常的调用返回顺序的方法;例外系统可以理解为某种时间机器。我在这里解释一下:

C#构造函数中的异常会导致来电者分配失败吗? [ ^ ],

存储位置.net操作系统中的例外情况 [ ^ ]。



请参阅我的其他过去的答案并提供一些基本建议:

处理类库中的异常(dll) [ ^ ],

异常详细信息:System.Runtime.InteropServices.COMException:检索具有CLSID {0006F03A-0000-0000-C000-的组件的COM类工厂000000000046}由于以下错误而失败:... [ ^ ],

扔。 .then ... rethrowing [ ^ ],

当我运行一个应用程序时,会遇到如何处理这个问题的异常? [ ^ ],

如何制作一个循环停止时滚动条到达底部 [ ^ ],

保持ac#windows form appl尽管存在任何未处理的异常,但仍在运行 [ ^ ],

未处理的例外:访问违规 [ ^ ] ,

错误记录和屏幕截图。 [ ^ ],

捕获例外 [ ^ ]。



但是你应该明白,在每种情况下,真正精炼的策略应该来自对机制的深刻理解以及对代码设计,开发和维护的适当经验。 br $>


-SA
All wrong, without any exclusions. That was the purpose of structural exception handling to avoid such situations.

Maybe, only the first case deserve some comment. This code is logically equivalent to not handling exceptions at all, but practically it is wasteful: it just spends some extra resources, including development and support of those superfluous lines, nothing else. The exception should be re-thrown only for certain purpose: to create selective handling at some point, by exception type or on some condition. In such cases, some of the conditional situation is handled locally, and some are re-thrown up the stack (do you understand stack operation? this is the key), to be handled elsewhere. Also, it is important not to handle exceptions locally. One of the most important purposes of the mechanism is to minimize handling and neatly separate "normal" execution flow from exceptional; therefore, in most places in the code, exceptions should just go, propagate further up the stack, which is achieved by not handling exceptions.

So, what to do? First you need to get some basic understanding on how exception works. This is a way to bypass normal call-return order based on call stack; exceptions system can be understood as some kind of "time machine". I explained it here:
Does Exception in C# Constructor Cause Caller Assignment to Fail?[^],
where was stored .net exceptions in operating system[^].

Please see my other past answers with some basic recommendations:
Handling exceptions in class library (dll)[^],
Exception Details: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error:...[^],
throw . .then ... rethrowing[^],
When i run an application an exception is caught how to handle this?[^],
How do i make a loop that will stop when a scrollbar reaches the bottom[^],
Keep a c# windows form application running despite any unhandled exception[^],
Unhandled Exception : Access Violation[^],
Error Logging and Screen Shot.[^],
Catching an Exception[^].

But you should understand that real refined strategy in each cases should come from deep understanding of the mechanism and appropriate experience with code design, development and maintenance.

—SA