Search code examples
c#error-handlingtry-catch-finally

Using Try-Catch-Finally to handle arithmetic exceptions


I would like to try TWO different things (both have a strong possibility of failure) and for this reason I would like to use the "finally" statement to run a "safety" just in case the first two tries both fail.

Take the following example (no this is not the code I am using in my project!).

int zero = 0;
int one = 1;

try
{
    // Throws ' cannot divide by zero ' error
    int error = one / zero;
}

catch
{
    // Throws error again of course
    int somenum = one / zero;
}

finally 
{
    MessageBox.Show("I can never make it here ..."); 
}

So, I would like for my program to do the following:

  1. Attempt to divide by zero
  2. If step #1 fails, I would like for the 'catch' statement to run its code (which should once again fail in this example).
  3. IF both steps #1 and #2 fail, I would like for my program to display the MessageBox in the 'finally' statement.

Am I even close with this one?


Solution

  • int zero = 0;
    int one = 1;
    
    try {
        try
        {
            // Throws ' cannot divide by zero ' error
            int error = one / zero;
        }
    
        catch (DivideByZeroException)
        {
            // Throws error again of course
            int somenum = one / zero;
        }
    }
    catch (DivideByZeroException)
    {
        MessageBox.Show("I can never make it here ...");
    }