在C#中分配多个Catch块
我们可以定义自己的自定义异常类型。
假设你想定义一个 CustomException
类。
类可能看起来像这样:
public class CustomException : System.Exception { //Default constructor public CustomException() : base() { } //Argument constructor public CustomException(String message) : base(message) { } //Argument constructor with inner exception public CustomException(String message, Exception innerException) : base(message, innerException) { } //Argument constructor with serialization support protected CustomException( SerializationInfo info, StreamingContext context) : base(info, context) { } }
我们可以为要创建的任何自定义异常使用此基本设置。
没有特殊的代码(除非你想添加它),因为 base()
条目意味着代码依赖于所找到的代码 System.Exception
。
你在这里看到的是遗产的工作。
换句话说,现在,我们不必担心此自定义异常如何工作。
现在考虑这一点 catch
条款在这里使用: public void SomeMethod() { try { SomeOtherMethod(); } catch(CustomException ce) { } }
如果什么 SomeOtherMethod()
抛出了一个简单的例外或者另一个 non-CustomException
类型 exception
?
这将是试图用棒球手套抓住足球 - 捕获不符合投掷。
幸运的是,使程序能够定义众多 catch
条款,每个人都设计用于不同类型的例外。
假设这是处理其他例外的正确的地方,你可以接一个地钉一个。
你必须排队多个 catch
不同异常类型的条款类型鼻子到尾部后 try
堵塞。
每一个都会cchecks catch
按顺序块,将抛出的对象与 catch
条款的参数类型,如此代码中所示:
public void SomeMethod() { try { SomeOtherMethod(); } catch(CustomException ce) //Most specific exception type { //All CustomException objects are caught here. } //You could insert other exception types between these two. catch(Exception e) //Most general exception type { //All otherwise uncaught exceptions are caught here. //Not that you should always do so -- but when it makes sense ... } }
是 SomeOtherMethod()
扔一个 Exception
对象,它会通过它 catch(CustomException)
因为一个 Exception
不是一种类型的 CustomException
。
它将被下一个抓住 catch
条款: catch(Exception)
。
总是排队 catch
来自最特定于最常一般的条款。
永远不要放置更多的一般 catch
第一个条款,如在这种相当糟糕的代码中:
public void SomeMethod() { try { SomeOtherMethod(); } catch(Exception e) //Most general first -- not good! { //All exceptions are caught here. //The dingo ate everything. } catch(CustomException ce) { //No exception ever gets this far, because it's //caught and consumed by the more general catch clause. } }
越一般 catch
条款饿死了 catch
通过拦截任何后面的条款 throw
。
编译器警告我们此错误。
Any class that inherits CustomException IS_A CustomException: class MySpecialException : CustomException { //. . . whatever .. . }
鉴于机会,一个 CustomException catch
抓住A. MySpecialException
像青蛙NABs飞行的对象。