简体   繁体   English

C#/ ASP-引发异常

[英]C# / ASP - Exceptions throwing

Is it a good idea to throw exceptions like "ArgumentException" in ASP? 在ASP中抛出诸如“ ArgumentException”之类的异常是一个好主意吗? I red some articles, and I know exceptions that I throw go to the Page_Error method. 我加了一些文章,而且我知道抛出的异常将转到Page_Error方法。 After this, execution is stuck here forever. 之后,执行将永远停留在这里。 How can I continue execution after Page_Error? Page_Error之后如何继续执行?

Or should I don't use throw and make something like this: 还是我不应该使用throw进行如下操作:

person.name = "blablabla";
if (person.NameValidatingError) Response.Write ("Ooops");

If you expect the argument to conform to some kind of validation rules and the passed in argument does not conform to them (and you can't recover), it is a good idea to throw an ArgumentException explaining why it was rejected. 如果您希望参数符合某种验证规则,而传入的参数不符合验证规则(并且您无法恢复),则最好抛出ArgumentException解释其被拒绝的原因。

You should, in page_error then redirect to an error page. 您应该在page_error重定向到错误页面。

您应该为整个应用程序提供一个错误页面,并将所有异常转移到该页面。

Instead of checking a variable after setting something, you would encapsulate it in a try / catch block if you know it could throw an error. 如果知道会引发错误,则可以将其封装在try / catch块中,而不是在设置某些内容后检查变量。

Like this: 像这样:

try
   person.name = "blablabla"
catch ex as YourExceptionType
   messagebox.show("There was an error in the foobar")
end try

... continue code here

It does not matter if we are talking about C# or Asp.Net but the matter is if it's a good practice throw exceptions. 我们在谈论C#还是Asp.Net都没有关系,但问题是是否抛出异常是一种好习惯。 In General you should throw exception only when is strictly needed as the exception throwing can leads the performance(sometime even hide the stack-trace). 通常,只有在严格需要时才应抛出异常,因为异常抛出会导致性能下降(有时甚至会隐藏堆栈跟踪)。 Another aspect is that an exception is something that you could not foresee perhaps when you were coding that feature but not something that you already know it could happen/avoid happening I would suggest you to avoid throwing exception as much as possible then if it is requirement in your domain you may create an error page to redirect to every time you get an unmanaged exception. 另一个方面是,当您对该功能进行编码时,您可能无法预见到异常,但是您已经知道它不会发生/避免发生的事情我建议您尽量避免抛出异常,如果有必要的话在您的域中,您可能会创建一个错误页面,以便在每次收到非托管异常时重定向到该页面。

If the method can handle the error on its own without putting the code in an invalid state, then there is no need to throw an exception. 如果该方法可以自行处理错误而无需将代码置于无效状态,则无需引发异常。

Otherwise, the method should throw an exception, leaving it up to the caller to decide if it knows how to handle the exception, or leave it uncaught. 否则,该方法应引发异常,由调用者决定是否知道如何处理该异常,或者将其保留。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM