If I have nested functions in C#, how to exit from both function at once when executing inner function code. (Return;
only exits from executing function.)
public void Function1()
{
Function2();
}
public void Function2()
{
if (1 == 1)
{
//Exit from both functions
}
}
Use return codes instead of void functions. Function1 can return if Function2 fails like so:
public void Function1()
{
if (Function2() == false)
return;
// do other code if Function2 succeeded
}
public bool Function2()
{
if (1 == 1)
{
return false;
}
else
{
return true;
}
}
The only way to return from a stack of functions simultaneously is to throw an exception. An exception will work it's way down the call stack until it finds an appropriate handler.
public class MyException : Exception
{
}
public void FunctionZero()
{
try
{
Trace.WriteLine("Function0 - Calling Function 1");
Function1();
Trace.WriteLine("Function0 - Function1 has returned");
}
catch(MyExceptionType ex)
{
Trace.WriteLine("Function0 - in the exception handler");
}
}
public void Function1()
{
Trace.WriteLine("Function1 - Calling Function 2");
Function2();
Trace.WriteLine("Function1 - Function2 has returned");
}
public void Function2()
{
if (1==1)
{
// This will jump to the exception handler in function zero
Trace.WriteLine("Function2 - throwing an exception");
throw new MyException();
}
}
Thiw will create the following trace output
Function0 - Calling Function 1
Function1 - Calling Function 2
Function2 - Throwing an exception
Function0 - In the exception handler
While you CAN do this, it's not necessarily a good idea. Standard coding practice is for Exceptions only to be used in exceptional circumstances, and not for normal flow control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With