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;
}
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
}
}
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 catch
ing 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.
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