问题
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