温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在java7中实现异常处理

发布时间:2021-05-26 10:43:01 来源:亿速云 阅读:145 作者:Leah 栏目:编程语言

如何在java7中实现异常处理?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

在Java 6中处理不同的异常

public Configuration getConfig(String fileName) {
 Configuration cfg = null;
 try {
  String fileText = getFile(fileName);
  cfg = verifyConfig(parseConfig(fileText));
 } catch (FileNotFoundException fnfx) {
  System.err.println("Config file '" + fileName + "' is missing");
 } catch (IOException e) {
  System.err.println("Error while processing file '" + fileName + "'");
 } catch (ConfigurationException e) {
  System.err.println("Config file '" + fileName + "' is not consistent");
 } catch (ParseException e) {
  System.err.println("Config file '" + fileName + "' is malformed");
 }
 return cfg;
}

这个方法会遇到的下面几种异常:

  • 配置文件不存在;

  • 配置文件在正要读取时消失了;

  • 配置文件中有语法错误;

  • 配置文件中可能包含无效信息。

这些异常可以分为两大类。一类是文件以某种方式丢失或损坏,另一类是虽然文件理论上存在并且是正确的,却无法正常读取(可能是因为网络或硬件故障)。

如果能把这些异常情况简化为这两类,并且把所有“文件以某种方式丢失或损坏”的异常放在一个catch语句中处理会更好。在Java 7中就可以做到:

在Java 7中处理不同的异常

public Configuration getConfig(String fileName) {
 Configuration cfg = null;
 try {
  String fileText = getFile(fileName);
  cfg = verifyConfig(parseConfig(fileText));
 } catch (FileNotFoundException|ParseException|ConfigurationException e) {
  System.err.println("Config file '" + fileName +
            "' is missing or malformed");
 } catch (IOException iox) {
  System.err.println("Error while processing file '" + fileName + "'");
 }
 return cfg;
}

异常e的确切类型在编译时还无法得知。这意味着在catch块中只能把它当做可能异常的共同父类(在实际编码时经常用Exception或Throwable)来处理。

另外一个新语法可以为重新抛出异常提供帮助。开发人员经常要在重新抛出异常之前对它进行处理。在前几个版本的Java中,经常可以看到下面这种代码:

try {
 doSomethingWhichMightThrowIOException();
 doSomethingElseWhichMightThrowSQLException();
} catch (Exception e) {
 ...
 throw e;
}

这会强迫你把新抛出的异常声明为Exception类型——异常的真实类型却被覆盖了。

不管怎样,很容易看出来异常只能是IOException或SQLException。既然你能看出来,编译器当然也能。下面的代码中用了Java 7的语法,只改了一个单词:

try {
 doSomethingWhichMightThrowIOException();
 doSomethingElseWhichMightThrowSQLException();
} catch (final Exception e) {
 ...
 throw e;
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI