开发者

Throw exception with method by given parameter C#

开发者 https://www.devze.com 2023-02-08 17:33 出处:网络
I wantto 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

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 except开发者_高级运维ion);
    }

}


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.


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();
    }
);


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).


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


Wouldn't it just be:

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号