唯一的潛在問題是您正在捕捉非特定的Exception
,因此不符合exception handling guidelines。
下列情況之一的將是更符合的這些準則:
try
{
DoSomething();
}
catch(SomeException ex)
{
throw new LibraryException(ex.Message, ex);
}
或:
try
{
DoSomething();
}
catch(Exception ex)
{
if (ex is SomeException || ex is SomeOtherException)
{
throw new LibraryException(ex.Message, ex);
}
throw;
}
至於性能,一旦異常被拋出,一些特殊情況已經發生了,你可能不關心包裝它的小額外開銷。
從評論:
在大多數情況下
當庫選擇包裝異常,將包裹被扔進庫的範圍之外的所有異常,...
我不同意與此,雖然它是公認的主觀。它包裝異常庫的一個例子是SqlMembershipProvider
,它封裝了一些具體的例外在ProviderException
,例如:
try
{
new Regex(this._PasswordStrengthRegularExpression);
}
catch (ArgumentException exception)
{
throw new ProviderException(exception.Message, exception);
}
但其他異常,如SqlException
呼叫者不能指望處理傳播展開。
來源
2012-09-26 14:15:22
Joe
想知道,這是如何幫助你知道發生異常的地方?所有異常都有一個堆棧跟蹤,爲什麼你不能使用它? – Hogan
這已被問到之前,請參閱:http://stackoverflow.com/questions/4761216/c-throwing-custom-exception-best-practices http://stackoverflow.com/questions/22623/net-throwing-exceptions- best-practices –