介绍
如何在java7中实现异常处理?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
<强>在Java 6中处理不同的异常强>
public Configuration getConfig (String 文件名),{ ,Configuration cfg =,空; ,try { String 才能;fileText =, getFile(文件名); 时间=cfg 才能;verifyConfig (parseConfig (fileText)); ,}catch (FileNotFoundException fnfx), { System.err.println才能(“Config  file & # 39;“, +, fileName +,“& # 39;, is missing"); ,}catch (IOException e), { System.err.println才能(“Error  while processing file & # 39;“, +, fileName +,“& # 39;“); ,}catch (ConfigurationException e), { System.err.println才能(“Config  file & # 39;“, +, fileName +,“& # 39;, is not consistent"); ,}catch (ParseException e), { System.err.println才能(“Config  file & # 39;“, +, fileName +,“& # 39;, is malformed"); ,} ,return cfg; }
<强>这个方法会遇到的下面几种异常:强>
- <李>
配置文件不存在,
李> <李>配置文件在正要读取时消失了;
李> <李>配置文件中有语法错误;
李> <李>配置文件中可能包含无效信息。
李>这些异常可以分为两大类。一类是文件以某种方式丢失或损坏,另一类是虽然文件理论上存在并且是正确的,却无法正常读取(可能是因为网络或硬件故障)。
如果能把这些异常情况简化为这两类,并且把所有“文件以某种方式丢失或损坏”的异常放在一个捕捉语句中处理会更好。在Java 7中就可以做到:
<强>在Java 7中处理不同的异常强>
public Configuration getConfig (String 文件名),{ ,Configuration cfg =,空; ,try { String 才能;fileText =, getFile(文件名); 时间=cfg 才能;verifyConfig (parseConfig (fileText)); ,}catch (FileNotFoundException | ParseException | ConfigurationException e), { System.err.println才能(“Config  file & # 39;“, +, fileName + ,,,,,,,,,,,“& # 39;,is missing 或是malformed"); ,}catch (IOException iox), { System.err.println才能(“Error  while processing file & # 39;“, +, fileName +,“& # 39;“); ,} ,return cfg; }
异常e的确切类型在编译时还无法得知。这意味着在catch块中只能把它当做可能异常的共同父类(在实际编码时经常用异常或Throwable)来处理。
另外一个新语法可以为重新抛出异常提供帮助。开发人员经常要在重新抛出异常之前对它进行处理。在前几个版本的Java中,经常可以看到下面这种代码:
try { ,doSomethingWhichMightThrowIOException (); ,doSomethingElseWhichMightThrowSQLException (); },catch (Exception e), { ,…… ,throw e; }
这会强迫你把新抛出的异常声明为异常类型——异常的真实类型却被覆盖了。
不管怎样,很容易看出来异常只能是IOException或SQLException异常。既然你能看出来,编译器当然也能。下面的代码中用了Java 7的语法,只改了一个单词:
try { ,doSomethingWhichMightThrowIOException (); ,doSomethingElseWhichMightThrowSQLException (); },catch (final Exception e), { ,…… ,throw e; }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。