user602996
user602996

Reputation:

Throw exception with method by given parameter C#

I want to make a method, that throws a specific exception, by a parameter I give to the method. I have 3 userdefined exceptions, so instead of having to throw them every time I want to use them I want to make a method that handels it, so the parameter I give with my method is the exception I want to throw, but how do I do that?

I want to do something like this, but I am not really sure how to do it.

private void ExceptionMethod(custom exception)
{
    try
    {
       //code that might fail
    }
    catch(exception ex)
    {
      throw new exception given by parameter(parameters from the exception);
    }

}

Upvotes: 1

Views: 3892

Answers (5)

ChrisF
ChrisF

Reputation: 137128

You were actually quite close:

private void ExceptionMethod(Exception customException)
{
    try
    {
       //code that might fail
    }
    catch(Exception ex)
    {
        throw customException;
    }
}

Will work, though I wouldn't recommend it for two reasons:

  1. Catching Exception is a bad idea - you should just catch the exceptions that your code raises.
  2. It's not a very good design (as others have pointed out).

Upvotes: 2

Yannick Motton
Yannick Motton

Reputation: 35971

Apart from the fact that this sounds like a bad idea, you can try the following:

private void TryElseThrow<TCustomException>(Action codeThatMightFail)
    where TCustomException : Exception
{
    try
    {
        codeThatMightFail();
    }
    catch (Exception e)
    {
        // Since there isn't a generic type constraint for a constructor
        // that expects a specific parameter, we'll have to risk it :-)
        throw
          (TCustomException)Activator
            .CreateInstance(typeof(TCustomException), e);
    }
}

Use like so:

TryElseThrow<MyCustomException>(
    () =>
    {
        throw new InvalidOperationException();
    }
);

Upvotes: 5

Steve Dunn
Steve Dunn

Reputation: 21751

Wouldn't it just be:

private void ExceptionMethod(MyCustomException exception)
{
    try
    {
       //code that might fail
    }
    catch
    {
      throw exception;
    }

}

Upvotes: 0

Shekhar_Pro
Shekhar_Pro

Reputation: 18420

So i dont see any problem in that.. as you say you already have your Custom Exception Written then you can do it like this.

in your parameter:

private void ExceptionMethod(CustomException myexception)

in catch:

throw myexception;

though its not a good Coding Design

Upvotes: 0

Tim Jarvis
Tim Jarvis

Reputation: 18815

FWIW I don't think this is a particulary good idea. Really, just throw your exception where it occurs, future maintainers of the code will thank you. (or at least not curse you)

If you have to do this thing, then its probably a better idea to pass an enumeration that you can switch on rather than the exception itself, then simply write a case statement to throw the exception you want.

Upvotes: 5

Related Questions