0
我在C#中發現了一些關於異常過濾的question。我想爲它寫一些模擬。我不知道它對人有什麼幫助,我也沒有使用VB過濾。當然,這不是優化和生產準備,但工作和做必須做的事情(我怎麼理解這個問題)。所以工作草圖:帶過濾的C#異常監視器
using System;
namespace ExceptionFiltering
{
class ExceptionMonitor
{
Action m_action = null;
public ExceptionMonitor(Action action)
{
this.m_action = action;
}
public void TryWhere(Func<Exception, bool> filter)
{
try
{
this.m_action();
}
catch (Exception ex)
{
if (filter(ex) == false)
{
throw;
}
}
}
public static void TryWhere(Action action, Func<Exception, bool> filter)
{
try
{
action();
}
catch (Exception ex)
{
if (filter(ex) == false)
{
throw;
}
}
}
}
class Program
{
//Simple filter template1
static Func<Exception, bool> m_defaultExceptionFilter = ex =>
{
if (ex.GetType() == typeof(System.Exception))
{
return true;
}
return false;
};
//Simple filter template2
static Func<Exception, bool> m_notImplementedExceptionFilter = ex =>
{
if (ex.GetType() == typeof(System.NotImplementedException))
{
return true;
}
return false;
};
static void Main(string[] args)
{
//Create exception monitor
ExceptionMonitor exMonitor = new ExceptionMonitor(() =>
{
//Body of try catch block
throw new Exception();
});
//Call try catch body
exMonitor.TryWhere(m_defaultExceptionFilter);
//Call try catch body using static method
ExceptionMonitor.TryWhere(() =>
{
//Body of try catch block
throw new System.NotImplementedException();
}, m_notImplementedExceptionFilter);
//Can be syntax like ExceptionMonitor.Try(action).Where(filter)
//Can be made with array of filters
}
}
}
待辦事項:全局異常處理程序,支持多個過濾器等;
謝謝你的任何建議,更正和優化!
什麼是你的問題? – cdhowie 2010-11-24 16:43:14
@cdhowie:我認爲這個問題是'你的建議是什麼?' – 2010-11-24 16:45:16