对于一般编码中的异常,不要“捕捉了异常却什么也不做”。如果隐藏了一个异常,你将永远不知道异常到底发生了没有。发生异常时,给出友好的消息给用户,但要精确记录错误的所有可能细节,包括发生的时间,和相关方法,类名等。只捕捉特定的异常,而不是一般的异常。
好:
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (FileIOException ex)
{
// log error.
// re-throw exception depending on your case.
throw;
}
}
不好:
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (Exception ex)
{
// Catching general exception is bad… we will never know whether it
// was a file error or some other error.
// Here you are hiding an exception.
// In this case no one will ever know that an exception happened.
return "";
}
}
不必在所有方法中捕捉一般异常。不管它,让程序崩溃。这将帮助你在开发周期发现大多数的错误。你可以用应用程序级(线程级)错误处理器处理所有一般的异常。遇到“意外的一般性错误”时,此错误处理器应该捕捉异常,给用户提示消息,在应用程序关闭或用户选择“忽略并继续”之前记录错误信息。不必每个方法都用try-catch。当特定的异常可能发生时才使用。比如,当你写文件时,处理异常FileIOException。别写太大的 try-catch 模块。如果需要,为每个执行的任务编写单独的 try-catch 模块。这将帮你找出哪一段代码产生异常,并给用户发出特定的错误消息如果应用程序需要,可以编写自己的异常类。自定义异常不应从基类SystemException派生,而要继承于IApplicationException。
异常处理
不要“捕捉了异常却什么也不做”。如果隐藏了一个异常,你将永远不知道异常到底发生了没有。发生异常时,给出友好的消息给用户,但要精确记录错误的所有可能细节,包括发生的时间,和相关方法,类名等。只捕捉特定的异常,而不是一般的异常。
好:
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (FileIOException ex)
{
// log error.
// re-throw exception depending on your case.
throw;
}
}
不好:
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (Exception ex)
{
// Catching general exception is bad… we will never know whether it
// was a file error or some other error.
// Here you are hiding an exception.
// In this case no one will ever know that an exception happened.
return "";
}
}
不必在所有方法中捕捉一般异常。不管它,让程序崩溃。这将帮助你在开发周期发现大多数的错误。你可以用应用程序级(线程级)错误处理器处理所有一般的异常。遇到“意外的一般性错误”时,此错误处理器应该捕捉异常,给用户提示消息,在应用程序关闭或用户选择“忽略并继续”之前记录错误信息。不必每个方法都用try-catch。当特定的异常可能发生时才使用。比如,当你写文件时,处理异常FileIOException。别写太大的 try-catch 模块。如果需要,为每个执行的任务编写单独的 try-catch 模块。这将帮你找出哪一段代码产生异常,并给用户发出特定的错误消息如果应用程序需要,可以编写自己的异常类。自定义异常不应从基类SystemException派生,而要继承于IApplicationException。