我可能不理解这个问题,但不是实际中断(这似乎不可能),而是在表达式树中放置一个 try-catch 并记录异常就足够了吗?
static void Main(string[] args)
{
var logExceptionMethod = typeof (Program).GetMethod("LogException", BindingFlags.Static | BindingFlags.NonPublic);
var createFileMethod = typeof (System.IO.File).GetMethod("Create", new[] {typeof(string)});
// Parameter for the catch block
var exception = Expression.Parameter(typeof(Exception));
var expression =
Expression.TryCatch(
Expression.Block(typeof(void),
// Try to create an invalid file
Expression.Call(createFileMethod, Expression.Constant("abcd/\\"))),
// Log the exception from the catch
Expression.Catch(exception, Expression.Call(logExceptionMethod, exception)));
Expression.Lambda<Action>(expression).Compile()();
}
static void LogException(Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}
控制台输出:
The filename, directory name, or volume label syntax is incorrect.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.Create(String path)
at lambda_method(Closure )