Change Exception and throw it

I want to change the property Messagein Exceptionwith more information. For example, generated SQLfrom EF.

But I do not want to lose anything from the original Exception. This will make me lose stacktrace:

catch (Exception ex)
{
    throw ex;
}

These Exceptioncome from the data layer. And I want throwthem so that they can be registered with Elmah.

What are my options?

+4
source share
5 answers

If you want to add something, you can simply wrap it in another exception:

catch( Exception ex)
{
   throw new Exception("my new message",ex);
}

and you can access the internal exception with a full stack trace

0
source

:

public class CustomException : Exception
{
    public CustomException()
        : base()
    {
    }

    public CustomException(string message)
        : base(message) 
    { 
    }

    public CustomException(string message, Exception innerException)
        : base(message, innerException)
    { 
    }

//...other constructors with parametrized messages for localization if needed
}

catch (Exception ex)
{
    throw new CustomException("Something went wrong", ex);
}

, . , , , .

, , . , . , . , Exception, , .

+3

: . . , ( ) "" .

, . , , .

, / , . , , :

catch (SomeEntityFrameworkException ex)
{
    throw new MyCustomException("Some additional info", ex);
}
+1

I would just make my own exception containing the original exception and any additional information you want, create a new exception in your catch block and throw it away

0
source

Just do:

catch (Exception ex)
{
    throw;
}

This eliminates further exception without re-throwing and retains context.

-1
source

Source: https://habr.com/ru/post/1529322/


All Articles