Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel the execution of a method?

Tags:

c#

Consider i execute a method 'Method1' in C#. Once the execution goes into the method i check few condition and if any of them is false, then the execution of Method1 should be stopped. how can i do this, i.e can the execution of a method when certain conditions are met.?

but my code is something like this,

int Method1()
{
    switch(exp)
    {
        case 1:
        if(condition)
            //do the following. **
        else
            //Stop executing the method.**
        break;
        case2:
        ...
    }
}
like image 237
SyncMaster Avatar asked Apr 13 '09 14:04

SyncMaster


People also ask

How do you stop a method call?

Run your temp method as runnable in a single thread. And interrupt it after 20 seconds. Catch the interrupt exception. In your main class now wait for 20 seconds and call the stop() method.

How do I stop a method execution in C#?

Use the continue Statement to Exit a Function in C# The continue statement skips the execution of a block of code when a certain condition is true. Unlike the break statement, the continue statement transfers the control to the beginning of the loop. Below is an example of code using a foreach method.


2 Answers

I think this is what you are looking for.

if( myCondition || !myOtherCondition )
    return;

Hope it answered your question.

Edit:

If you want to exit the method due to an error you can throw an exception like this:

throw new Exception( "My error message" ); 

If you want to return with a value, you should return like before with the value you want:

return 0;

If it is the Exception you need you can catch it with a try catch in the method calling your method, for instance:

void method1()
{
    try
    {
        method2( 1 );
    }
    catch( MyCustomException e )
    {
        // put error handling here
    }

 }

int method2( int val )
{
    if( val == 1 )
       throw new MyCustomException( "my exception" );

    return val;
}

MyCustomException inherits from the Exception class.

like image 125
Jesper Fyhr Knudsen Avatar answered Oct 12 '22 23:10

Jesper Fyhr Knudsen


Use the return statement.

if(!condition1) return;
if(!condition2) return;

// body...
like image 43
mmx Avatar answered Oct 13 '22 00:10

mmx