0

Will Jon Skeet feed me to his pet unicorn if I do something like the following?

private void TakeTheRisk()
{
    try
    {
        ...
        DoRiskyBusiness();
        ...
    }
    catch (SomeException ex)
    {
        ProcessAndRethrowException(ex);
    }
}

private async Task TakeYetAnotherRiskAsync()
{
    try
    {
        ...
        await DoEvenMoreRiskyBusinessAsync();
        ...
    }
    catch (SomeException ex)
    {
        ProcessAndRethrowException(ex);
    }
}

private void ProcessAndRethrowException(SomeException ex)
{
    ...
    throw; // given to understand `throw ex;` will lose stack trace, right?
}

Main motivation is to commonize exception processing logic. This processing logic is non-trivial and I would prefer to not need to duplicate it. Is it possible to somehow refactor it out of TakeTheRisk and TakeYetAnotherRiskAsnyc into ProcessAndRethrowException as above?

Bondolin
  • 2,793
  • 7
  • 34
  • 62
  • Have you tried this? IMO, you should just test/debug on your own, to get your desired result – Blue Nov 26 '19 at 12:44
  • You can also create an AggregateException, or a custom exception, with an `InnerException` being the target you want. – Blue Nov 26 '19 at 12:45
  • 1
    Note that `ProcessAndRethrowException` can't just use `throw;` - that's only valid in a catch block. You might want to consider using an exception filter instead. – Jon Skeet Nov 26 '19 at 13:12
  • Not sure I'm getting my point across. The question is not how to catch this or that exception, so much as I have some non-trivial logic processing the exception, and I'd rather not duplicate it in two separate `catch` blocks. Furthermore, and I'm editing the question to include this, while I would normally just encapsulate the whole `try`...`catch` into a common method, the second function is `async`, so I don't have that option. – Bondolin Nov 26 '19 at 13:47
  • BTW @JonSkeet you didn't answer my first question - am I unicorn snack? – Bondolin Nov 26 '19 at 17:12
  • @Bondolin: If you want to end up not actually catching the exception, but just processing it and then rethrowing it, an exception filter works well for that. Or put the `throw` part in the catch block as normal. Yes, it's fine to call a method with the exception as an argument – Jon Skeet Nov 26 '19 at 17:31

0 Answers0