我根據異常類型插入不同的消息。異常鑄造
我想根據異常類型在異常表中插入不同的自定義消息。我不能使用switch語句和異常對象。
有關我如何做到這一點的任何建議?
private void ExceptionEngine(Exception e)
{
if (e.)
{
exceptionTable.Rows.Add(null, e.GetType().ToString(), e.Message);
}
我根據異常類型插入不同的消息。異常鑄造
我想根據異常類型在異常表中插入不同的自定義消息。我不能使用switch語句和異常對象。
有關我如何做到這一點的任何建議?
private void ExceptionEngine(Exception e)
{
if (e.)
{
exceptionTable.Rows.Add(null, e.GetType().ToString(), e.Message);
}
if (e is NullReferenceException)
{
...
}
else if (e is ArgumentNullException)
{
...
}
else if (e is SomeCustomException)
{
...
}
else
{
...
}
和那些if
條款,你可以投e
到相應的異常類型來檢索此異常的某些特定屬性裏面:((SomeCustomException)e).SomeCustomProperty
如果所有的代碼將在的if/else塊那麼最好使用多次捕獲(記得把最具體的類型第一):
try {
...
} catch (ArgumentNullException e) {
...
} catch (ArgumentException e) { // More specific, this is base type for ArgumentNullException
...
} catch (MyBusinessProcessException e) {
...
} catch (Exception e) { // This needs to be last
...
}
我不能使用switch語句和異常對象。
如果你想使用一個開關,你總是可以使用類型名稱:
switch (e.GetType().Name)
{
case "ArgumentException" : ... ;
}
這有可能的優點是,你不比賽亞型。
字符串標識符非常難看。 – CodesInChaos 2011-05-01 10:19:24
或typeof(ArgumentException).ToString()。我不確定,但這可能是好的。 – Homam 2011-05-01 10:23:14
@Jack你需要一個常數來使用開關/外殼。沒有開關/外殼,根本沒有理由使用字符串。此代碼的另一個問題是名稱衝突。不同的異常類可能具有相同的名稱。 – CodesInChaos 2011-05-01 10:27:27
您可以通過預定義的字典來統一處理不同的異常類型(編譯時已知)。例如:
// Maps to just String, but you could create and return whatever types you require...
public static class ExceptionProcessor {
static Dictionary<System.Type, Func<String, Exception> sExDictionary =
new Dictionary<System.Type, Func<String, Exception> {
{
typeof(System.Exception), _ => {
return _.GetType().ToString();
}
},
{
typeof(CustomException), _ => {
CustomException tTmp = (CustomException)_;
return tTmp.GetType().ToString() + tTmp.CustomMessage;
}
}
}
public System.String GetInfo(System.Exception pEx) {
return sExDictionary[pEx.GetType()](pEx);
}
}
用法:
private void ExceptionEngine(Exception e) {
exceptionTable.AddRow(ExceptionProcessor.GetInfo(e));
}
是否有可能使用SWTICH /回事呢? – Homam 2011-05-01 10:19:29
@傑克,不是一個可以接受的方式。見@亨克霍爾特曼[答案](http://stackoverflow.com/questions/5847741/exception-casting/5847799#5847799)。 – 2011-05-01 10:20:45
謝謝,我不喜歡處理字符串。我認爲你的解決方案更好。 – Homam 2011-05-01 10:22:34