Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I check the type of an exception from within a function?

I have the following code:

        catch (ServiceException e) { se(e); return View("CreateEdit", vm); }
        catch (Exception e) { ex(e); return View("CreateEdit", vm); }
        return RedirectToAction("ShowSummary", new {
                    ds = vm.Meta.DataSourceID
        });

    protected void se(ServiceException e) {
        ModelState.Merge(e.Errors);
    }
    protected void ex(Exception e) {
        Trace.Write(e);
        ModelState.AddModelError("", "Database access error: " + e.Message);
    }

I would like to change this to something like:

        catch (Exception e) { processException(e); return View("CreateEdit", vm); }

Is there a way that I can add code to a processException function that would be able to check what kind of exception it is and then do action depending on if it is a ServiceException or just a general exception? I just want to put all my exception handling in one place and then call it.

Upvotes: 0

Views: 295

Answers (3)

competent_tech
competent_tech

Reputation: 44931

Absolutely, we use this extensively in database exception handling.

public void processException(Exception ex)
{
   if (ex is System.Threading.ThreadAbortException)
   {
      // Do something
   }
   else if (ex is AnotherException)
   {
      // Do something else
   }
}

Upvotes: 1

Adam
Adam

Reputation: 16199

You can use the typeOf(e) or e.GetType() and then do a switch or if statement on that.

Upvotes: 1

Roman
Roman

Reputation: 10403

You can use the is keyword like this

protected void processException(Exception e) {
    if (e is XXXException)
    {
        this.doThis();
    }
    else if (e is YYYException)
    {
        this.doThat();
    }
}

You can also use a switch statement and test the type of the e but IMO is is easier and better

Upvotes: 4

Related Questions