Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping function after exception

Tags:

c#

I'm having some issues with creating an error handling method. After encountering an error, the sub continues as if nothing happened. This is what I have:

try 
{
    int numericID = Convert.ToInt32(titleID);
}
catch(Exception)
{
    errorHandling("Invalid Title");
}

void errorHandling(string error)
{
    MessageBox.Show("You have encountered an error: " + error, "Error");
    return;
}
like image 988
Mason Hanson Avatar asked Mar 15 '23 05:03

Mason Hanson


2 Answers

try 
    {
        int numericID = Convert.ToInt32(titleID);
    }
    catch(Exception)
    {
        errorHandling("Invalid Title");
        return; // <---- perhaps you wanted to put the return here?
    }

void errorHandling(string error)
{
    MessageBox.Show("You have encountered an error: " + error, "Error");
    // return; <-- does nothing
}

Is it code in other functions which you want to hault execution of when exception is caught? Just make a global boolean:

bool exceptionCaught = false;

....

try 
    {
        int numericID = Convert.ToInt32(titleID);
    }
    catch(Exception)
    {
        errorHandling("Invalid Title");
        exceptionCaught = true;
        return; // <---- perhaps you wanted to put the return here?
    }

void errorHandling(string error)
{
    MessageBox.Show("You have encountered an error: " + error, "Error");
    // return; <-- does nothing
}

....

void OtherMethod()
{
    if(!exceptionCaught)
    {
        // All other logic
    }
}
like image 177
maksymiuk Avatar answered Mar 28 '23 14:03

maksymiuk


What do you want to happen?

Some common things are bubbling up the exception...

    try 
    {
        int numericID = Convert.ToInt32(titleID);
    }
    catch(Exception)
    {
        errorHandling("Invalid Title");

        // rethrow the error after you handle it
        //
        throw;
    }

Or you could log the error in your errorHandling() method.

Or you can return from your parent method where the exception was thrown.

Either way, you're catching the exception, and you're executing errorHandling() method, but at that point the catch block is done with its execution... so code continues.

Whatever you want to happen... make it happen in the catch block, or you're just silencing errors. If you don't want execution to continue, then don't allow execution to continue, but you need to explicitly write the code for that in the catch block.

like image 42
Thomas Stringer Avatar answered Mar 28 '23 16:03

Thomas Stringer