简体   繁体   English

如何在 c# 中抛出异常但不停止进程?

[英]How to throw an exception but do not stop the process in c#?

I'm trying to show a message on the screen but I don't want to end the process.我正在尝试在屏幕上显示一条消息,但我不想结束该过程。 Is there any way of doing it?有什么办法吗?

        var nonValidPolicies = Policies2RedistributeBankStatementAmountFor.Where(p => p.PolicyIsNotValid);
        if (nonValidPolicies.Any())
            throw new UserFriendlyException("Something");

When you have an exception, that means the code is not working, as desired, at the run time.当您遇到异常时,这意味着代码在运行时无法正常工作。 When the exception is thrown, the control jumps to the parent method to look for the exception handler (try-catch).当抛出异常时,控件跳转到父方法寻找异常处理程序(try-catch)。 In case the handler is missing, the control goes one method higher and so on.如果缺少处理程序,则控件将转到更高的一种方法,依此类推。

In order to address the problem of continuity, try to break the whole method into smaller methods.为了解决连续性问题,尝试将整个方法分解为更小的方法。 The idea is to corner out the troublesome code which might throw exception, and wrap it inside a try-catch.这个想法是消除可能引发异常的麻烦代码,并将其包装在 try-catch 中。 And in the parent method handle it gracefully.并在父方法中优雅地处理它。

Now, looking at the code snippet given above, it is absolutely a bad idea to throw exception for a known problem.现在,查看上面给出的代码片段,对于已知问题抛出异常绝对是一个坏主意。 Exceptions should be for the scenarios which are unknown at the runtime like connection failure, items not found etc. In the above scenario, you are checking for existence of elements and throwing exception.异常应该针对运行时未知的场景,如连接失败、未找到项目等。在上述场景中,您正在检查元素是否存在并抛出异常。 Instead return a message, so that parent method knows it and handles the situation.而是返回一条消息,以便父方法知道它并处理这种情况。 Better to use asynchronous method.最好使用异步方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM