User 5842
User 5842

Reputation: 3029

Creating 2 Exceptions in a Finally Block

I have the following code:

finally
{
    if (!isDnsSet)
    {
        var exception = new Exception(<DNS-INFORMATION>);
                        localLog.TraceException(exception);
                        throw exception;
    }
}

As it stands, this exception throws too much information to the user that is not particularly needed for them to see. I want to be able to log exception using my localLog class but also throw another exception with a more concise message.

I was thinking to just create another exception with the shortened message and still log the original, more verbose one using my class.

Is there a more elegant way of doing this or would I just do something like:

var shortException = new Exception(<short and sweet message>);
var longException = new Exception(<not so short and sweet but still useful for other devs>);
localLog.TraceException(longException);
throw shortException;

Upvotes: 0

Views: 61

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

One approach is to create a custom exception that carries both a long and a short message. Users who get the exception outside your library would access the short message through Exception's Message property, while your TraceException method would access the long version through an additional property provided by your custom exception:

public class DetailedException : Exception {
    public string DetailedMessage { get; }
    public DetailedException(string longMessage, string shortMessage) : base(shortMessage) {
        DetailedMessage = longMessage;
    }
}

Inside TraceException method:

var message = (exception as DetailedException)?.DetailedMessage ?? exception.Message;

Upvotes: 1

D Stanley
D Stanley

Reputation: 152501

I think a cleaner method would be to make the longer exception an inner exception:

finally
{
    if (!isDnsSet)
    {
        var innerException = new Exception(<not so short and sweet but still useful for other devs>);
        var exception = new Exception(<short and sweet message>, innerException);
        localLog.TraceException(exception);
        throw exception;
    }
}

That way you have consistency between the exception that's thrown and the exception that's logged, making diagnosis easier.

Upvotes: 1

Brian
Brian

Reputation: 1248

Couldn't the exception handler receive and process the longException and, as part of its function, throw the shortException?

Upvotes: 0

Related Questions