try/catch/finally , How to prevent finally when i have return in my catch?
I have this code and i want to prevent finally execution
try
{
throw new Exception("Try Error!!!");
}
catch(Exception exp)
{
Console.Write开发者_C百科Line(exp.Message);
Console.ReadLine();
if(exp.Message == "Try Error!!!")
return;
}
finally
{
Console.WriteLine("Finally...");
Console.ReadLine();
}
But return doesn't work.
the finally doesn't run only in following three conditions :
- The System.exit() is called from the
try
orcatch
block. - There is an infinite loop inside the try block.
- The system crashes or power loss while executing the try block.
for all other conditions .... the finally is always executed... having a boolean variable to control the execution of finally code is a clever approach... go for it...
That's the point of finally - it always runs.
try this:
bool runfinally = true;
try {
throw new Exception("test");
} catch {
runfinally = false;
} finally {
if(runfinally) {
// do stuff.
}
}
Why would you want to do that?
Finally is there so it allways runs and does some finishing work which has to be done anyway, if ou want the code to be executed only when the try runs then write in in the try statement, otherwise if only when it fails then in the catch one. Code that has to tun in both cases has to be written in the finally section.
The only way is to set a flag variable that your finally
code tests, e.g.:
bool handled = false;
try
{
throw new Exception("Try Error!!!");
}
catch(Exception exp)
{
Console.WriteLine(exp.Message);
Console.ReadLine();
if (exp.Message == "Try Error!!!")
{
handled = true;
return; // This isn't really necessary unless you have code below it you're not showing
}
}
finally
{
if (!handled)
{
Console.WriteLine("Finally...");
Console.ReadLine();
}
}
...but I'd really consider revisiting your logic so you don't need to do that. The whole point of finally
is that no matter what happens within the try
block, that finally
code will run, whether you return early from the code in the try
block, or an exception occurs, or you return from within the catch
block.
The whole point of finally is that it runs regardless of how the try/catch block executed. One workaround can be something like this:
bool runfinallycode = true;
try
{
throw new Exception("Try Error!!!");
}
catch(Exception exp)
{
Console.WriteLine(exp.Message);
Console.ReadLine();
if(exp.Message == "Try Error!!!")
runfinallycode = false;
}
finally
{
if( runfinallycode )
{
Console.WriteLine("Finally...");
Console.ReadLine();
}
}
Finally gets executed no matter what happens in the try catch block. It's meant that way so that you can free up resources before you exit the function.
System.exit() can be used to avoid the execution of the finally block Finally Block. But if your condition is that the execution should not be hindered, then please do reframe the question.
But your return is in a if clause so it will not always work. Try putting it outside the if in catch
精彩评论