gpt4 book ai didi

c# - 是否有可能不中断某些异常的执行流程但中断其他异常 - 如果是这样,如何?

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:57 25 4
gpt4 key购买 nike

我需要从外部框架调用多个方法 - 或者更确切地说,我正在围绕它编写一个包装器,供其他用户以非预定顺序从该框架调用方法。现在框架的一些方法会抛出异常,即使没有“真正的”错误发生。基本上它们应该是内部异常,只是为了通知任何人之前已经执行过要执行的操作。例如:一个文件已经加载。下次加载文件不会有什么坏处,所以就我而言,这个“错误”根本就不是错误。所以我需要继续处理这个异常,但我还需要捕获其他真正的异常,例如当连接到客户端和其他东西的框架无法这样做时。

下面我有一些(极其简化的)示例代码。显然,该代码无法编译,因为自定义异常的代码丢失了。同样在现实生活中,代码分布在三个程序集中。这意味着,我无法将异常处理程序包装在那些只会抛出 InternalFrameworkException() 的框架方法周围。我只能将它包裹在整个 SomeMethod() 周围。正如我所写,这是一个极其简化的示例。

有什么方法可以处理 RealException()s 但不使用 PostSharp 继续 InternalFrameworkException()s如前所述here ?请注意,这并不是让 InternalFrameworkException() 失败,而是它们实际上根本不应该突破 try{} block 。

namespace ExceptionTest
{
using System;

internal class Program
{
private static void Main(string[] args)
{
try
{
SomeMethod();
}
catch (InternalFrameworkException exception)
{
// Do not actually catch it - but also dont break the
// execution of "SomeMethod()".
// Actually I never want to end up here...
}
catch (RealException exception)
{
// Break the execution of SomeMethod() as usual.
throw;
}
catch (Exception exception)
{
// Again, break the execution of SomeMethod() as usual.
throw;
}
finally
{
// Clean up.
}
}

#region == Method is actually contained in another assembly referencing this assembly ===

private static void SomeMethod()
{
// Should break if uncommented.
// MethodThrowingProperException();
// Should not break.
MethodThrowingInternalExceptionOrRatherContinuableError();
// Should execute, even if previously an internal framework error happened.
MethodNotThrowingException();
}

#endregion

#region ===== Framework methods, they are contained in a foreign dll =====

private static void MethodThrowingProperException()
{
// Something happened which should break execution of the
// application using the framework
throw new RealException();
}

private static void MethodThrowingInternalExceptionOrRatherContinuableError()
{
// Perform some stuff which might lead to a resumable error,
// or rather an error which should not break the continuation
// of the application. I.e. initializing a value which is
// already initialized. The point is to tell the application using
// this framework that the value is already initialized, but
// as this wont influence the execution at all. So its rather
// a notification.
throw new InternalFrameworkException();
}

private static void MethodNotThrowingException()
{
// Well, just do some stuff.
}

#endregion
}
}

编辑:我确实尝试了帖子中的例子我已经linked above ,它就像一个魅力......仅在 SomeMethod() 中使用它时。我可以理论上实现这个,因为我包装了所有在 SomeMethod() 中调用的方法,然后再将它们暴露给最终程序集,但我不喜欢这种方法,因为它会给我的代码带来不必要的复杂性。

最佳答案

当抛出异常时,执行流程就被打断了。你可以捕获异常,也可以不捕获异常,但抛出异常后你不能“继续”。

不过,您可以将逻辑分成几部分,并在抛出异常时继续下一部分。

关于c# - 是否有可能不中断某些异常的执行流程但中断其他异常 - 如果是这样,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24235135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com