Exit from a function in C#

风流意气都作罢 提交于 2019-12-10 12:55:50

问题


A basic question. I need to exit a function without throwing any exceptions. How do I do that in C#?


回答1:


It's just as simple as:

void Function()
{
    ...

    if(needToLeave)
        return;

    ...
}

Nevertheless this would be a one minute search in any programming tutorial.




回答2:


I'm not sure I understand you correctly. Maybe using return;?




回答3:


Instead of using "return;" I've always suggested a right logic.

In other words, you don't need to leave execution from some method: just use a conditional statement so if some boolean isn't true, that would mean some code mustn't be executed.

But I assume this is my opinion, and others prefer returning the control to the caller.

Additionally, you'd like to know exception-based flow control is an anti-pattern.




回答4:


Use the return or break keywords ...... But make sure nothing is after these statements as you may have unreachable code. Also having multiple exits in your code can make it difficult to maintain in the future




回答5:


you can put you code in a try catch block and do whatever you want to do in the finally block without worrying about the exception.

 try
        {
         //try something   
        }
        catch(Exception ex)
        {
            //catch all exceptions and log on need basis
            //but do not throw the exception from here
        }
        finally
        {
            return "Test";
            //do what ever you want to do 
        }



回答6:


May be to Keep the catch block empty. Please explain your question



来源:https://stackoverflow.com/questions/5855991/exit-from-a-function-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!