aca*_*lon 26 c# vb.net debugging visual-studio
在C#应用程序中,我想要的是:
未附加调试器时: -
附加调试器时: -
为了举例说明,下面是它如何使用条件catch(我知道在C#中不支持):
注意:虽然我正在显示我的代码抛出异常的示例,但它可能会被第三方库抛出.
static void DoSomething()
{
//This is where I would like the debugger to break execution and show the exception
throw new Exception( "Something went wrong!" );
}
static public void DoSomeStep()
{
try
{
DoSomething();
}
catch( Exception exception when System.Diagnostics.Debugger.IsAttached == false ) //If the debugger is attached don't catch
{
Console.WriteLine( exception.Message ); //Do some processing on the exception
}
}
static void Main( string[] args )
{
for( int i = 0; i < 10; i++ )
{
DoSomeStep();
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个大问题,因为有堆栈跟踪和日志记录将信息拼凑在一起,但我想知道是否有一个很好的方法来实现这一点,因为它偶尔出现(并且是那千个削减中的一个)我不介意没有).另外,我从未找到过理想的方法,所以如果有的话,我感兴趣.
在具有许多步骤(例如运行测试)的程序中尤其相关.在正常的独立操作期间,如果这些步骤中的任何一个引发异常,则应记录错误并执行应转移到下一步.但是,在调试器中运行时,调试器应该在引发异常的位置中断.这将加快调试过程,因为您不需要查询堆栈跟踪,并且将保留局部变量的状态.
这个问题的其余部分描述了我已经尝试过的事情,以便在答案中不再重复......
我知道C#不支持这种功能,但VB.NET支持它.因此,我可以通过在VB.NET库中实现以下内容来获得所需的行为(不要太担心代码,它基本上包装了一个方法,try...catch如果存在异常且调试器是,则调用错误处理程序没有附上):
Public Module DebuggerNoCatch
Public Function Run(Of T, U, V, W, X)(func As Func(Of T, U, V, W, X, Boolean), arg1 As T, arg2 As U, arg3 As V, arg4 As W, context As X, errorHandler As Action(Of System.Exception, X)) As Boolean
Dim result As Boolean = False
Try
result = func(arg1, arg2, arg3, arg4, context)
Catch ex As Exception When Not Debugger.IsAttached
errorHandler(ex, context)
result = False
End Try
Return result
End Function
End Module
Run Code Online (Sandbox Code Playgroud)
请注意,Run根据参数的数量,需要有不同的重载(在这种情况下,我恰好使用4个参数).此外,还有一个Context参数用于需要在被调用方法和错误处理程序之间维护某些状态的情况.
然后我的代码看起来像这样:
static bool DoSomething( int a, int b, int c, int d, RunContext context )
{
//Now the debugger break at this point - hooray!
throw new Exception( "Something went wrong!" );
return true;
}
static void HandleException( Exception exception, RunContext context )
{
//Only see this when not attached in the debugger
Console.WriteLine( exception.Message ); //Do some processing on the exception
}
class RunContext{ } //context information - not used in this example
static public void DoSomeStep()
{
DebuggerNoCatch.Run<int, int, int, int, RunContext>( DoSomething, 1, 1, 1, 1, new RunContext(), HandleException );
}
Run Code Online (Sandbox Code Playgroud)
这种方法的缺点是: -
try...catch- 其他人第一次来到代码时需要深入了解究竟发生了什么.代码(注意throw):
例:
static public void DoSomeStep()
{
try
{
DoSomething();
}
catch( Exception exception )
{
Console.WriteLine( exception.Message ); //Do some processing on the exception
//If the debugger is attached throw, otherwise just continue to the next step
if( System.Diagnostics.Debugger.IsAttached == true )
{
//This is where the debugger breaks execution and shows the exception
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,在throw保留堆栈跟踪的同时,调试器会在发生抛出的行而不是原始抛出处中断.完全可以理解它是以这种方式发生的,但它并不是我想要发生的事情.这意味着我需要查看堆栈跟踪的异常,然后找到正确的代码行.此外,发生异常的局部变量的状态也会丢失.
基本上,只需将其包装try...catch在一个单独的方法中:
static void DoSomething()
{
//This is where I would like the debugger to break execution and show the exception
throw new Exception( "Something went wrong!" );
}
static void DoSomethingContinueOnError()
{
try
{
DoSomething();
}
catch( Exception exception )
{
Console.WriteLine( exception.Message ); //Do some processing on the exception
}
}
static public void DoSomeStep()
{
if( System.Diagnostics.Debugger.IsAttached == false )
{
DoSomethingContinueOnError();
}
else
{
DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这有很多问题:
try...catch,如果存在子步骤则需要通过引用将其传递到"DoSomething".这可能是我最不喜欢的选择.在这种情况下,使用了一个条件编译符号,例如DEBUGGING(注意DEBUG不起作用,因为我可能在没有附加编译器的情况下运行DEBUG):
#if !DEBUGGING
try
#endif
{
DoSomething();
}
#if !DEBUGGING
catch( Exception exception )
{
Console.WriteLine( exception.Message ); //Do some processing on the exception
}
#endif
}
Run Code Online (Sandbox Code Playgroud)
问题是: -
#DEBUGGING使代码混乱并使try...catch可读性降低.Steven Liekens的评论表明什么似乎是一个很好的解决方案 - DebuggerStepThroughAttribute.当在包含重新抛出的方法上设置此属性时,调试器会在异常的原始位置中断,而不是在重新抛出的位置,如下所示:
static bool DoSomething()
{
//This is where the debugger now breaks execution
throw new Exception( "Something went wrong!" );
return true;
}
[DebuggerStepThrough]
static public void DoSomeStep()
{
try
{
DoSomething();
}
catch( Exception exception )
{
Console.WriteLine( exception.Message );
if( Debugger.IsAttached == true )
{
//the debugger no longer breaks here
throw;
}
}
}
static void Main( string[] args )
{
for( int i = 0; i < 10; i++ )
{
DoSomeStep();
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的缺点是,如果您确实想要进入标记为的代码DebuggerStepThrough或此代码中存在异常.虽然,这是一个小缺点,因为您通常可以保持这个代码最小.
注意使用Debugger.IsAttached因为我认为它在这里的影响是微小的,并且奇怪的heisenbugs的可能性是最小的,但要注意使用Guillaume在评论中指出并使用其他选项,如适当的配置设置.
除非有更好的方式或有人对此提出疑虑,否则我将继续这样做.
如果您使用的是C#6,则使用新的异常过滤器语法很容易做到这一点:
try
{
DoSomething()
}
catch (Exception e) when (!System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine(exception.Message);
}
Run Code Online (Sandbox Code Playgroud)
正如在注释中指出的那样,当在DebuggerStepThroughAttribute包含重新抛出的方法上设置时,调试器会在异常的原始点处中断,而不是在重新抛出的位置,如下所示:
static bool DoSomething()
{
//This is where the debugger now breaks execution
throw new Exception( "Something went wrong!" );
return true;
}
[DebuggerStepThrough]
static public void DoSomeStep()
{
try
{
DoSomething();
}
catch( Exception exception )
{
Console.WriteLine( exception.Message );
if( Debugger.IsAttached == true )
{
//the debugger no longer breaks here
throw;
}
}
}
static void Main( string[] args )
{
for( int i = 0; i < 10; i++ )
{
DoSomeStep();
}
}
Run Code Online (Sandbox Code Playgroud)
我花了一些时间编写一个LINQ启发的try...catch包装器,它实际上支持条件捕获块.
用法示例
在深入研究代码之前,这是一个基于原始要求的用法示例:
DangerousOperation
.Try(() =>
{
throw new NotImplementedException();
})
.Catch((NotImplementedException exception) =>
{
Console.WriteLine(exception.Message);
}).When(ex => !Debugger.IsAttached)
.Catch((NotSupportedException exception) =>
{
Console.WriteLine("This block is ignored");
}).When(ex => !Debugger.IsAttached)
.Catch<InvalidProgramException>() /* specifying a handler is optional */
.Catch() /* In fact, specifying the exception type is also optional */
.Finally(() =>
{
Console.WriteLine("Goodbye");
}).Execute();
Run Code Online (Sandbox Code Playgroud)
这是通过When()在执行语句中的任何内容之前首先评估语句中指定的谓词来实现的Catch().
如果您运行该示例,您将注意到调试器在导致异常的行上中断,因为该[DebuggerStepThrough]属性是巧妙放置的结果.
源代码
/// <summary>
/// Factory. Provides a static method that initializes a new try-catch wrapper.
/// </summary>
public static class DangerousOperation
{
/// <summary>
/// Starts a new try-catch block.
/// </summary>
/// <param name="action">The 'try' block's action.</param>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock"/> class that wraps the 'try' block.</returns>
public static TryCatchBlock Try()
{
return new TryCatchBlock();
}
/// <summary>
/// Starts a new try-catch block.
/// </summary>
/// <param name="action">The 'try' block's action.</param>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock"/> class that wraps the 'try' block.</returns>
public static TryCatchBlock Try(Action action)
{
return new TryCatchBlock(action);
}
}
/// <summary>
/// Wraps a 'try' or 'finally' block.
/// </summary>
public class TryCatchBlock
{
private bool finalized;
/// <summary>
/// Initializes a new instance of the <see cref="TryCatchBlock"/> class;
/// </summary>
public TryCatchBlock()
{
this.First = this;
}
/// <summary>
/// Initializes a new instance of the <see cref="TryCatchBlock"/> class;
/// </summary>
/// <param name="action">The 'try' or 'finally' block's action.</param>
public TryCatchBlock(Action action)
: this()
{
this.Action = action;
}
protected TryCatchBlock(TryCatchBlock antecedent)
{
if ( antecedent == null )
{
throw new ArgumentNullException("antecedent");
}
if ( antecedent.finalized )
{
throw new InvalidOperationException("This block has been finalized with a call to 'Finally()'");
}
this.First = antecedent.First;
this.Antecedent = antecedent;
antecedent.Subsequent = this;
}
protected TryCatchBlock(TryCatchBlock antecedent, Action action)
: this(antecedent)
{
this.Action = action;
}
public Action Action { get; set; }
/// <summary>
/// Gets the 'try' block.
/// </summary>
public TryCatchBlock First { get; private set; }
/// <summary>
/// Gets the next block.
/// </summary>
public TryCatchBlock Antecedent { get; private set; }
/// <summary>
/// Gets the previous block.
/// </summary>
public TryCatchBlock Subsequent { get; private set; }
/// <summary>
/// Creates a new 'catch' block and adds it to the chain.
/// </summary>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock{TException}"/> class that wraps a 'catch' block.</returns>
public TryCatchBlock<Exception> Catch()
{
return new TryCatchBlock<Exception>(this);
}
/// <summary>
/// Creates a new 'catch' block and adds it to the chain.
/// </summary>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock{TException}"/> class that wraps a 'catch' block.</returns>
public TryCatchBlock<Exception> Catch(Action<Exception> action)
{
return new TryCatchBlock<Exception>(this, action);
}
/// <summary>
/// Creates a new 'catch' block and adds it to the chain.
/// </summary>
/// <typeparam name="TException">The type of the exception that this block will catch.</typeparam>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock{TException}"/> class that wraps a 'catch' block.</returns>
public TryCatchBlock<TException> Catch<TException>() where TException : System.Exception
{
return new TryCatchBlock<TException>(this);
}
/// <summary>
/// Creates a new 'catch' block and adds it to the chain.
/// </summary>
/// <typeparam name="TException">The type of the exception that this block will catch.</typeparam>
/// <param name="action">The 'catch' block's action.</param>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock{TException}"/> class that wraps a 'catch' block.</returns>
public TryCatchBlock<TException> Catch<TException>(Action<TException> action) where TException : System.Exception
{
return new TryCatchBlock<TException>(this, action);
}
/// <summary>
/// Creates a new 'finally' block and finalizes the chain.
/// </summary>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock"/> class that wraps the 'finally' block.</returns>
public TryCatchBlock Finally()
{
return new TryCatchBlock(this) { finalized = true };
}
/// <summary>
/// Creates a new 'finally' block and finalizes the chain.
/// </summary>
/// <param name="action">The 'finally' block's action.</param>
/// <returns>Returns a new instance of the <see cref="TryCatchBlock"/> class that wraps the 'finally' block.</returns>
public TryCatchBlock Finally(Action action)
{
return new TryCatchBlock(this, action) { finalized = true };
}
/// <summary>
/// Gets a value indicating whether this 'catch' wrapper can handle and should handle the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>Returns <c>true</c> if the exception can be handled; otherwise <c>false</c>.</returns>
public virtual bool CanHandle(Exception exception)
{
return false;
}
/// <summary>
/// Handles the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
public virtual void Handle(Exception exception)
{
throw new InvalidOperationException("This is not a 'catch' block wrapper.");
}
/// <summary>
/// Executes the chain of 'try-catch' wrappers.
/// </summary>
//[DebuggerStepThrough]
public void Execute()
{
TryCatchBlock current = this.First;
try
{
if ( current.Action != null )
{
current.Action();
}
}
catch ( Exception exception )
{
while ( current.Subsequent != null )
{
current = current.Subsequent;
if ( current.CanHandle(exception) )
{
current.Handle(exception);
break;
}
if ( current.Subsequent == null )
{
throw;
}
}
}
finally
{
while ( current.Subsequent != null )
{
current = current.Subsequent;
if ( current.finalized && current.Action != null )
{
current.Action();
}
}
}
}
}
/// <summary>
/// Wraps a 'catch' block.
/// </summary>
/// <typeparam name="TException">The type of the exception that this block will catch.</typeparam>
public class TryCatchBlock<TException> : TryCatchBlock where TException : System.Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="TryCatchBlock{TException}"/> class;
/// </summary>
/// <param name="antecedent">The 'try' or 'catch' block that preceeds this 'catch' block.</param>
public TryCatchBlock(TryCatchBlock antecedent)
: base(antecedent) { }
/// <summary>
/// Initializes a new instance of the <see cref="TryCatchBlock{TException}"/> class;
/// </summary>
/// <param name="antecedent">The 'try' or 'catch' block that preceeds this 'catch' block.</param>
/// <param name="action">The 'catch' block's action.</param>
public TryCatchBlock(TryCatchBlock antecedent, Action<TException> action)
: base(antecedent)
{
this.Action = action;
}
/// <summary>
/// Sets a predicate that determines whether this block should handle the exception.
/// </summary>
/// <param name="predicate">The method that defines a set of criteria.</param>
/// <returns>Returns the current instance.</returns>
public TryCatchBlock<TException> When(Predicate<TException> predicate)
{
this.Predicate = predicate;
return this;
}
/// <summary>
/// Gets a value indicating whether this 'catch' wrapper can handle and should handle the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <returns>Returns <c>True</c> if the exception can be handled; otherwise false.</returns>
public override bool CanHandle(Exception exception)
{
if ( exception == null )
{
throw new ArgumentNullException("exception");
}
if ( !typeof(TException).IsAssignableFrom(exception.GetType()) )
{
return false;
}
if ( Predicate == null )
{
return true;
}
return Predicate((TException) exception);
}
/// <summary>
/// Handles the specified exception.
/// </summary>
/// <param name="exception">The exception.</param>
public override void Handle(Exception exception)
{
if ( this.Action != null )
{
this.Action((TException) exception);
}
}
/// <summary>
/// Gets the exception handler.
/// </summary>
public Action<TException> Action { get; private set; }
/// <summary>
/// Gets the predicate that determines whether this wrapper should handle the exception.
/// </summary>
public Predicate<TException> Predicate { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
最后的笔记
这是对我原帖的巨大修改.查看我的初始解决方案的更改历史记录.
| 归档时间: |
|
| 查看次数: |
2487 次 |
| 最近记录: |