14

When I use Try/Catch, is there a way just like If/Else to run code if there is no error is detected and no Catch?

try
{
    //Code to check
}
catch(Exception ex)
{
    //Code here if an error
}

//Code that I want to run if it's all OK ?? 

finally
{
    //Code that runs always
}
4

5 回答 5

33

Add the code at the end of your try block. Obviously you will only ever get there if there wasn't an exception before:

try {
  // code to check

  // code that you want to run if it's all ok
} catch {
  // error
} finally {
  // cleanup
}

You probably should change your catch in a way that you only catch exceptions you expect and not flat-out everything, which may include exceptions thrown in »code that you want to run if it's all ok«.

于 2012-07-31T11:00:13.780 回答
18

If you need it to always execute if your try code succeeds, put it at the end of your try block. It will run as long as the previous code in your try block runs without an exception.

try
{
    // normal code

    // code to run if try stuff succeeds
}
catch (...)
{
    // handler code
}
finally
{
    // finally code
}

If you need alternative exception handling for you "succeded" code, you can always nest your try/catches:

try
{
    // normal code

    try
    {
        // code to run if try stuff succeeds
    }
    catch (...)
    {
        // catch for the "succeded" code.
    }
}
catch (...)
{
    // handler code
    // exceptions from inner handler don't trigger this
}
finally
{
    // finally code
}

If your "succeeded" code has to execute after your finally, use a variable:

bool caught = false;
try
{
    // ...
}
catch (...)
{
    caught = true;
}
finally
{
    // ...
}

if(!caught)
{
    // code to run if not caught
}
于 2012-07-31T11:01:36.667 回答
6

Just place it after the code that may throw an exception.

If an exception is thrown it will not run, if one is not thrown, it will run.

try
{
    // Code to check
    // Code that I want to run if it's all OK ??  <-- here
}
catch(Exception ex)
{
    // Code here if an error
}
finally
{
    // Code that runs always
}
于 2012-07-31T11:00:43.933 回答
1
try {
    // Code that might fail
    // Code that gets execute if nothing failed
}
catch {
    // Code getting execute on failure
}
finally {
    // Always executed
}
于 2012-07-31T11:01:49.630 回答
1

I would write it like this: If the call to a method ran fine then the success is merely the last thing within the try

try 
{
    DoSomethingImportant();
    Logger.Log("Success happened!");
}
catch (Exception ex)
{
    Logger.LogBadTimes("DoSomethingImportant() failed", ex);
}
finally 
{
    Logger.Log("this always happens");
}
于 2012-07-31T11:02:08.163 回答