System.Net.WebException vs. System.Exception
我正在用C#调用SOAP Web服务
我正在使用try-catch来捕获Web服务调用引发的所有异常。 将以下代码:
1 2 3 4 5 6 7 8 | try { Webservice.Method(); } catch (Exception) { //Code } |
能够捕获所有异常,包括基于Web的异常,例如Web服务不可用,互联网未连接,错误的响应代码等。或者,如果System.Exception没有捕获到System.Net.WebException类型的异常,我也应该使用
1 2 3 4 5 6 7 8 9 10 11 12 | try { Webservice.Method(); } catch (WebException) { //Code for web based exceptions } catch (Exception) { //Code } |
我不想为不同的异常使用单独的代码。 对于所有类型的异常,仅一个消息框指出"发生错误"就足够了。
if System.Exception does not catch exceptions of type
System.Net.WebException.
因为
I do not want separate code for different exceptions. Just one message
box stating"error occurred" is good enough for me for all types of
exceptions.
在那种特殊情况下,一个空的catch块就足够了(除了捕获System.Exception外)。但通常不认为这是一种好习惯。
1 2 3 4 5 6 7 8 | try { Webservice.Method(); } catch { // Show error } |
您可能会看到:例外最佳做法
异常是所有异常的基本实现,任何.NET异常类型都必须从Exception类继承。根据MSDN:
This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler.
但是,您通常希望遵循不捕获诸如Exception这样的广泛类别的最佳实践。在此处查看一些良好准则:
但是实际上,有时候您并不在乎代码执行是否失败,您只是想知道它是否失败。但是,如果您不关心代码失败或失败的原因,则可能需要检查代码以查看是否需要调用代码。
简而言之,异常将捕获所有从异常派生的对象。
但是,这样做是不明智的做法:
http://msdn.microsoft.com/en-us/library/ms182137.aspx