Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse catch for all catches

Tags:

c#

try-catch

is it possible to do something like the following:

I want to catch a custom exception and do something with it - easy: try {...} catch (CustomException) {...}

But then i want to run the code used in the "catch all" block still run some other code which is relevant to all catch blocks...

try
{
    throw new CustomException("An exception.");
}
catch (CustomException ex)
{
    // this runs for my custom exception

throw;
}
catch
{
    // This runs for all exceptions - including those caught by the CustomException catch
}

or do i have to put whatever i want to do in all exception cases (finally is not an option because i want it only to run for the exceptions) into a separate method/nest the whole try/catch in another (euch)...?

like image 481
JaySeeAre Avatar asked May 30 '13 15:05

JaySeeAre


3 Answers

I generally do something along the lines of

try
{ 
    throw new CustomException("An exception.");
}
catch (Exception ex)
{
   if (ex is CustomException)
   {
        // Do whatever
   }
   // Do whatever else
}
like image 145
James Avatar answered Nov 03 '22 15:11

James


You need to use two try blocks:

try
{
    try
    {
        throw new ArgumentException();
    }
    catch (ArgumentException ex)
    {
        Console.WriteLine("This is a custom exception");
        throw;
    }
}
catch (Exception e)
{
    Console.WriteLine("This is for all exceptions, "+
        "including those caught and re-thrown above");
}
like image 27
Servy Avatar answered Nov 03 '22 15:11

Servy


Just do the overall catch and check to see if the exception is that type:

try
{
   throw new CustomException("An exception.");
}
catch (Exception ex)
{
   if (ex is CustomException)
   {
       // Custom handling
   }
   // Overall handling
}

Alternately, have a method for overall exception handling that both call:

try
{
   throw new CustomException("An exception.");
}
catch (CustomException ex)
{
    // Custom handling here

    HandleGeneralException(ex);
}
catch (Exception ex)
{
   HandleGeneralException(ex);
}
like image 35
Deeko Avatar answered Nov 03 '22 16:11

Deeko