Declare a method that always throws an exception?

Viewed 12384

I have a method like:

int f() {
  try {
    int i = process();
    return i;
  } catch(Exception ex) {
    ThrowSpecificFault(ex);
  }
}

This produces a compiler error, "not all code paths return a value". But in my case ThrowSpecificFault() will always throw (the appropriate) exception. So I am forced to a put a return value at the end but this is ugly.

The purpose of this pattern in the first place is because "process()" is a call to an external web service but need to translate a variety of different exceptions to match a client's expected interface (~facade pattern I suppose).

Any cleaner way to do this?

13 Answers

@MuiBienCarlota was the right one for me since I was doing some logging.

Something like this

[DoesNotReturn]
protected void LogAndThrow(Exception ex)
{
    _log.LogError(ex, ex.Message);
    throw ex;
}
Related