How to cancel the execution of a method?

后端 未结 5 789
眼角桃花
眼角桃花 2020-12-30 08:18

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 shou

5条回答
  •  感动是毒
    2020-12-30 09:02

    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.

提交回复
热议问题