简体   繁体   中英

Rethrow Exception and Catch Again

I am using C# and wondered if it was possible to rethrow an exception from a try/catch and have a later catch statement recatch it?

try {
// 1. Try some operation
    //Failed operations

// 2. Throw an exception
    throw new IOException("I tried my best");
} catch(IOException) {
// 3. Try some specific recovery operation
    //Failed operations

//4. Rethrow and try again
    throw;
}

... Some more specific exception handlers

} catch(Exception) {
// 5. Re-caught here as a last-ditch effort, generic recovery operation
    //Process here
} finally {
    //...
}

Only if your catch statement throws to another try/catch, for example:

try{

    ...

   try{
        ...
   }
   catch(ExceptionA a)
   {
      throw;
   }
   catch(Exception e)
   {
       //will not not catch ExceptionA (rethrow or not)
   }
}
catch(ExceptionA a)
{
    //this would catch the re-throw
}
catch( Exception e)
{
}

Instead why don't you catch the general Exception and then case the exception types?

try{
        ...
   }
   catch(Exception e)
   {
       if (e is ExceptionA){
            ...
       }
   }

Or put logic on the finally

 System.Exception thrownException = null;
 try{
        ...
   }
   catch( ExceptionA a)
   {
      thrownException = a;
      ...  // do special handling...
   }
   catch( ExceptionB b)
   {
      thrownException = b;
      ...  // do special handling...
   }
   catch(Exception e)
   {
      ...
   }
   finally{
     if ( thrownException != null ) {
          ...   //case the type here or use some other way to identify..
     }
   }

Your code should work, however the real problem is that exceptions should be used to inform outer code parts about the fact, that something went wrong. Throwing MANUALLY an exception in the try section and catching it in the following catch section is pointless. If you know you can't process some IO operation, handle it right away with an if-else statement. Using try-catch for that is without a doubt a bad, inefficient practice.

Not sure (because of variables scope, because c# is not the language I'm now using, and because of possible side effects due to the new added variable, and because it does not look to be a good coding practice ), but would that work:

try{
     ...
}
catch(ExceptionA a)
{
   exception = a;  // "Store" the exception in a variable
}
catch(Exception e)
{
    //will not not catch ExceptionA (rethrow or not)
}

try
{
    if (exception)
        throw exception;  // kind of rethrow if variable is set
}
catch(ExceptionA a)
{
    //this would catch the re-throw
}
catch( Exception e)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM