如何解决所有异常类型都在普通的旧“异常”下被捕获吗?
| 我只是想更好地理解这一点。 我了解有很多不同的异常类型,根据我所做的一些阅读,所有异常类型都被Exception捕获。首先,我可以保证这是真的吗?try{
...
}
catch(Exception x){
//No matter what fails in the try block,x
//will always have a value since all exception
//types are caught under Exception? I guess
//What I really want to know,is will this ever
//Fail?
}
catch(SystemException x){
//This code will never execute since all
//exceptions are caught in the first catch?
}
接下来,该捕获层次结构如何工作?如果Exception位于顶部,其他所有异常类型是Exception下的一级,还是存在多个类型层,例如Exception是ExceptionSomething的父级,而ExceptionSomethingElse是ExceptionSomethingElse的父级?
附录:
或者,如果我们有这样的代码:
try{
...
}
catch(SystemException x){
//If there is an exception that is not a SystemException
//code in this block will not run,right (since this is
//looking specifically for SystemExceptions)?
}
解决方法
它实际上取决于您的.NET版本和配置。在C ++ / CLI中,您可以抛出任何东西。它不必是
Exception
。在1.1(IIRC)中,您只能使用catch块来捕获它们,例如:
catch {...}
这不是很有帮助-您看不到发生了什么。默认情况下,在2.0(IIRC)中,此类异常会自动包含在伪RuntimeWrappedException
子类中。但是,出于兼容性考虑,您可以关闭此功能。我求求你:不要:)
,是的,这可行,因为所有标准异常都继承自Exception
。
您的代码可以使用,但是您需要在所有特殊的异常类型之后加上ѭ2的处理程序。 (将执行第一个匹配的处理程序。)
不是从“ 2”继承的异常不会被捕获,因为它们不是指定的类型。但是.NET异常类都从该基类继承。
有人认为这不是一个好主意,但我通常只接受Exception
,除非我希望对特定的异常类型进行特殊处理。
,是的,Exception是从Object类继承的,所有异常都是从Exception类继承的。
上面的链接将向您显示所有异常的层次结构。
System.Object
System.Exception
Microsoft.Build.BuildEngine.InternalLoggerException
Microsoft.Build.BuildEngine.InvalidProjectFileException
Microsoft.Build.BuildEngine.InvalidToolsetDefinitionException
Microsoft.Build.BuildEngine.RemoteErrorException
...
其中一些异常,例如您提到的SystemException,还有从它们继承的其他异常,但是它们仍然都继承自Exception类:
System.Object
System.Exception
System.SystemException
Microsoft.SqlServer.Server.InvalidUdtException
System.AccessViolationException
System.Activities.ValidationException
System.AppDomainUnloadedException
System.ArgumentException
System.ArithmeticException
...
,为了回答问题的第二部分,.Net Framework中的异常层次结构示例:
ArgumentNullException inherits from
ArgumentException inherits from
SystemException inherits from
Exception
您应该尝试处理最具体的情况。
try{
//something
}
catch(ArgumentNullException ex){
//handle ArgumentNullException
}
catch(SystemException ex1)
{
//handle other kinds of SystemException
if(IDontWantToHandleThisExceptionHere(ex1))
{
throw;// not throw new Exception(ex1);
}
}
,后者可以从基类Exception
继承,也可以从继承基类的任何其他类继承。
例如:SqlException
从DbException
继承,DbException
从ExternalException
继承,ExternalException
从SystemException
继承,finally17ѭ最终从Exception
继承。
,是的,所有异常类型都继承自异常。
而且,继承的工作方式可以有多个级别的继承
MyAppException : Exception {
}
MyAppFileNotFoundException : MyAppException {
}
通常用于具有不同类型异常的不同行为
try {
openfile(\'thisFileDoesNotExist.txt\');
}
catch (MyAppFileNotFoundException ex)
{
//warn the user the file does not exist
}
catch (Exception ex)
{
//warn the user an unknown error occurred,log the error,etc
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。