繁体   English   中英

这是关于Java中的异常处理和异常匹配概念

[英]This is about the Exception Handling and the Exception Matching Concept in Java

我是Java新手。 我当时正在经历“异常处理概念”,但在这里我只停留在一点。 我们知道,每当抛出Exception时,Java都会尝试通过自上而下的方式查看可用的catch子句来查找。 如果找不到,则将在处理程序中查找Exception的超类型;如果未找到与该异常的超类型匹配的catch子句,则该异常将沿调用堆栈传播。

同样,如果将大多数特定的异常置于更通用的异常处理程序之上,则会导致COmpilation错误。

假设我们有如下所示的代码:

try{
    // do not know what kind of exception it will be throwing but I am sure that it is IOException
   }

try{
     // Here the FileNotFoundException is thrown
   }

catch(IOException e){
//Do exception handling stuff
}

catch(FileNotFoundException f){
  //Do exception handling stuff`
 }

现在,此代码将导致编译错误,因为异常的超类型位于实际异常之上。

那么为什么第一段不支持这个概念。 即在检查JVM之后将找到适当的异常(FileNotFoundException),并且不应理会IOException子句,而是会遇到编译错误。

请给它一些照明。 还可以让我知道我是否能够解释自己想要做什么?

看来您误会了尝试概念。 您只能先尝试一下catch子句。

try{
    // do not know what kind of exception it will be throwing but I am sure that it is IOException
   // Here the FileNotFoundException is thrown
}

catch(IOException e){
    //Do exception handling stuff
}

catch(FileNotFoundException f){
  //Do exception handling stuff`
 }

此代码将在编译时引发错误,因为对于FileNotFound Catch Block,该代码将无法访问,因为它已由IO Exception处理,并且FileNotFound是IOException的子类。

FileNotFoundException的不可用catch块。 它已由IOException的catch块处理。

FileNotFoundException是IOException的子类,它使我们可以选择是否将所有IOException视为相同,或者单独捕获某些IOExceptions子类。

代码段具有基本错误

如果try块中发生异常,则该异常由与其关联的异常处理程序处理。 要将异常处理程序与try块相关联,必须在其后放置catch块

推荐阅读:

https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

暂无
暂无

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

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