通过给定参数的方法抛出异常 C#
我想创建一个方法,通过我给该方法的参数抛出特定的异常。我有 3 个用户定义的异常,所以我不想每次使用它们时都抛出它们,而是想创建一个处理它的方法,所以我用我的方法给出的参数就是我想要抛出的异常,但是我该怎么做这样做吗?
我想做这样的事情,但我不太确定该怎么做。
private void ExceptionMethod(custom exception)
{
try
{
//code that might fail
}
catch(exception ex)
{
throw new exception given by parameter(parameters from the exception);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
FWIW 我认为这不是一个特别好的主意。实际上,只要在发生异常的地方抛出异常,代码的未来维护者就会感谢你。 (或者至少不会诅咒你)
如果你必须做这件事,那么最好传递一个可以打开的枚举而不是异常本身,然后简单地编写一个 case 语句来抛出你想要的异常。
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:
Use like so:
您实际上非常接近:
会起作用,但我不会推荐它,原因有两个:
Exception
是一个坏主意 - 您应该只捕获代码引发的异常。You were actually quite close:
Will work, though I wouldn't recommend it for two reasons:
Exception
is a bad idea - you should just catch the exceptions that your code raises.所以我没有看到任何问题......正如你所说,你已经编写了自定义异常,那么你可以这样做。
在你的参数中:
在 catch 中:
虽然它不是一个好的编码设计
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:
in catch:
though its not a good Coding Design
难道不就是:
Wouldn't it just be: