`
lantian_123
  • 浏览: 1360181 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Java SE 7 Exception的使用

 
阅读更多

Java SE 7 Exception的使用

Java SE 7 中,作为Project Coin项目中众多有用的细小语言变化之一的加强型异常处理,现在来学习如何利用它。

简介:

在这边文章中,我们所涉及的一些变化是作为Java平台标准版7(Java SE 7)所发布,在JSR334(Java Specification Request)有详细的说明。现在我们重点讨论异常处理,特别是:multi-catch,rethrow,以及try-with-resources.

 

Multi-Catch Exceptions

多异常捕获已经加入到Java SE 7,他帮助我们更简便的进行异常处理,现在就把你的异常处理代码从Java SE7之前的版本迁移到Java SE7来阅读。

1

 

public class ExampleExceptionHandling
{
   public static void main( String[] args )
   {
   try {
        URL url = new URL("http://www.yoursimpledate.server/");
        BufferedReader reader = new
              BufferedReader(newInputStreamReader(url.openStream()));
        String line = reader.readLine();
        SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
        Date date = format.parse(line);
   }
   catch(ParseException exception) {
        // handle passing in the wrong type of URL.
   }
   catch(IOException exception) {
        // handle I/O problems.
   }
   catch(ParseException exception) {
        // handle date parse problems.
   }
   }
}
 

 

在过去,如果你想要相同的逻辑代码在上面的三个异常代码块的时候,你不得不在PaseExceptionIOException中拷贝粘贴代码,一个缺乏经验或者懒惰的程序员可能认为像下面这样也是OK的。

2

 

public class ExampleExceptionHandlingLazy
{
   public static void main( String[] args )
   {
         try {
                  URL url = new URL("http://www.yoursimpledate.server/");
                  BufferedReader reader = new
             BufferedReader(new InputStreamReader(url.openStream()));
                  String line = reader.readLine();
                  SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
                  Date date = format.parse(line);
         }
         catch(Exception exception) {
                  // I am an inexperienced or lazy programmer here.
         }
   }
}
 

 

在例2代码示例中最大的毛病就是会产生不可预料的副作用,任何代码在try代码块可能产生异常,所有异常将全部由catch子句所处理。如果一个异常既不是ParseException也不是IOException(例如:SecurityException),此异常仍然会被捕获,但是上游用户去不知道真正发生了什么?这种吞并式的异常将很难调试。

 

为了方便程序员,JavaSE7现在引入了多异常捕获,这样程序员就可以合并多个catch字句为一个单独的代码块,而不需要去使用危险的吞并似的一个异常捕获所有,或者拷贝整个代码块。

例3:

 

public class ExampleExceptionHandlingNew
{
   public static void main( String[] args )
   {
         try {
                  URL url = new URL("http://www.yoursimpledate.server/");
                  BufferedReader reader = new BufferedReader(
                           new InputStreamReader(url.openStream()));
                  String line = reader.readLine();
                  SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
                  Date date = format.parse(line);
         }
         catch(ParseException | IOException exception) {
                  // handle our problems here.
         }
   }
}
 

 

示例3就展示了怎么合理的合并两个catch块语句,注意catch子句的语法(ParseException|IOException),catch子句可以捕获ParseExceptionIOException。所以如果想多个不同的异常共用相同的异常处理代码,那么就可以使用这种管道语法(ExceptionType…|ExceptionType variable)

 

Rethrowing Exceptions

当你在处理异常的时候,有时候想把一个处理完后的异常往外抛的时候,没有经验的程序员可能认为用下面这种方式操作是合理的

4

 

public class ExampleExceptionRethrowInvalid
{
   public static void demoRethrow()throws IOException {
         try {
                  // forcing an IOException here as an example,
                 // normally some code could trigger this.
                 throw new IOException(“Error”);
         }
         catch(Exception exception) {
                  /*
                   * Do some handling and then rethrow.
                   */
                  throw exception;
         }
   }
   
   public static void main( String[] args )
   {
         try {
                  demoRethrow();
                  }
         catch(IOException exception) {
         System.err.println(exception.getMessage());
         }
   }
}
 

很遗憾的是编译器没发完成编译工作,下面这段代码展示了如何去处理完异常后再往外抛。

5

 

public class ExampleExceptionRethrowOld
{
   public static demoRethrow() {
         try {
                  throw new IOException("Error");
         }
         catch(IOException exception) {
                  /*
                   * Do some handling and then rethrow.
                   */
                  throw new RuntimeException(exception);
         }
   }
   
   public static void main( String[] args )
   {
         try {
                  demoRethrow();
         }
         catch(RuntimeException exception) {
         System.err.println(exception.getCause().getMessage());
         }
   }
}
 

上面这个例子的毛病就在于不能抛出原生的异常,他用另外一个异常包裹了,这就意味着代码的下游需要注意他是被包装了的。所以为了捕获到这个确切的原生异常,在Java SE7中做出变化是必须的,如下代码:

6

 

public class ExampleExceptionRethrowSE7
{
   public static demoRethrow() throws IOException {
         try {
                  throw new IOException("Error");
         }
         catch(Exception exception) {
                  /*
                   * Do some handling and then rethrow.
                   */
                  throw exception;
         }
   }
   
   public static void main( String[] args )
   {
         try {
                  demoRethrow();
         }
         catch(IOException exception) {
         System.err.println(exception.getMessage());
         }
   }
}
 

上面的示例在JavaSE7中能正确的编译(译者注)

 

Try-with-Resources

你可能注意到了在第一个例子中有这样一个问题(这就是为什么当你不知道示例代码做了些什么的时候,你永远也不要在生产环境中使用)。这个问题就是没有对资源的清空。例7是一个修改的版本,描述了怎样在JavaSE7之前的版本中校正这个问题。

7

 

public class ExampleTryResources
{
   public static void main(String[] args)
   {
         BufferedReader reader = null;
   
         try {
                  URL url = new URL("http://www.yoursimpledate.server/");
                  reader = new BufferedReader(new 
                                   InputStreamReader(url.openStream()));
                  String line = reader.readLine();
                  SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
                  Date date = format.parse(line);
         }
         catch (MalformedURLException exception) {
                  // handle passing in the wrong type of URL.
         } catch (IOException exception) {
                  // handle I/O problems.
         } catch (ParseException exception) {
                  // handle date parse problems.
         } finally {
                  if (reader != null) {
                           try {
                                   reader.close();
                                    } catch (IOException ex) {
                                   ex.printStackTrace();
                           }
                  }
         }
   }
}
 

我们注意到代码中添加了一个final代码块,如果BufferedReader被赋值了,它将被关闭,而且变量reader也已经移到了try代码块的外面了。当一个I/O异常发生的时候关闭字符流就要多些很多的代码。

 

JavaSE7中,可以更简洁更清爽,如例8所示,这种新的语法允许你把资源作为try代码块的一部分,这意味着可以提前定义好资源然后执行完try代码块的时候虚拟机将自动关闭资源。

8

 

public static void main(String[] args)
{
   try (BufferedReader reader = new BufferedReader(
         new InputStreamReader(
         new URL("http://www.yoursimpledate.server/").openStream())))
   {
         String line = reader.readLine();
         SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
         Date date = format.parse(line);
   } catch (ParseException | IOException exception) {
         // handle I/O problems.
   }
}
 

在例8中实际发生变化的是在try(….)语句,需要注意的是这个特性只有在资源实例实现了AutoCloseable接口的实例才能生效

 

总结:

异常处理在javaSE7中,你不仅可以写出更简洁的程序,正如multi-catch示例所演示的一样,而且在可以处理完部分异常后再往外抛出去。如re_throw 例子所示,JavaSE7同样有助于减少易于出错的异常清理。正如我们在try-with resource例子中看到的一样。这些特征和其他Project Coin项目中提供的一样,能使Java程序员写代码更有效率以及写出更高效的代码。

 

附上自己的一点感受:第一次这样认真的去翻译一遍文章,以往看完一遍文章可以不到二十分钟,但是翻译工作花了我两个小时,非常认真的在做,发现翻译不仅可以学外语,还可以学语文。对自己的语言组织也有提高,终于体会到翻译书籍的人特别不容易。2012/3/1  1:20

 

原文连接http://www.oracle.com/technetwork/articles/java/java7exceptions-486908.html

 

3
1
分享到:
评论
5 楼 angel243fly 2012-03-02  
对翻译工作的辛苦深有体会
4 楼 sangshuye 2012-03-02  
论坛应该改下了。。。。。顶的可以不说理由,,,踩的一定说理由。。。。
3 楼 javabkb 2012-03-02  
赞楼主,讲得很好
2 楼 斌-黄 2012-03-02  
:idea:  ,不过说实话写起来更别扭了。
1 楼 chen592969029 2012-03-01  
给力,感谢分享~~~~

相关推荐

    JAVA SE 开发手册.CHM

    7、JAVA面向对象之三大特性 8、JAVA面向对象之函数、堆和栈、访问修饰符 9、JAVA面向对象关键字 10、JAVA面向对象抽象类abstract 11、JAVA面向对象接口interface 12、JAVA面向对象之内部类、匿名内部类 13、...

    java7帮助文档

    Oracle has two products that implement Java Platform Standard Edition (Java SE) 7: Java SE Development Kit (JDK) 7 and Java SE Runtime Environment (JRE) 7. JDK 7 is a superset of JRE 7, and contains ...

    Core Java Volume II 最新第8版 part1全两卷 (附随书源码)

    Fully updated for the new Java SE 6 platform, this no-nonsense tutorial and reliable reference illuminates the most important language and library features with thoroughly tested real-world examples....

    Java精华(免费版)

    1JAVA SE 1.1深入JAVA API 1.1.1Lang包 1.1.1.1String类和StringBuffer类 位于java.lang包中,这个包中的类使用时不用导入 String类一旦初始化就不可以改变,而stringbuffer则可以。它用于封装内容可变的字符串。它...

    JAVA_API1.6文档(中文)

    java.awt.im.spi 提供启用可以与 Java 运行时环境一起使用的输入方法开发的接口。 java.awt.image 提供创建和修改图像的各种类。 java.awt.image.renderable 提供用于生成与呈现无关的图像的类和接口。 java.awt....

    Java 1.6 API 中文 New

    Java SE Platform 软件包: java.applet 提供创建 applet 所必需的类和 applet 用来与其 applet 上下文通信的类。 java.awt 包含用于创建用户界面和绘制图形图像的所有类。 java.awt.color 提供用于颜色空间的类。 ...

    Core Java Volume I Fundamentals, 11th Edition

    The #1 Java Guide for Serious Programmers: Fully Updated for Java SE 9, 10 & 11 For serious programmers, Core Java, Volume I—Fundamentals, Eleventh Edition, is the definitive guide to writing robust,...

    OCP-1Z0-819:OCP Oracle认证专业Java SE 11开发人员实践

    OCP Oracle认证专业Java SE 11开发人员实践指南。 关键字词 配套 包是可选的。 流量控制 数组 内存中的对象 变量存储在Stack中。 对象存储在堆中。 对象引用是指针和变量,它们存储在Stack中。 例外情况 ...

    java自动发邮件

    java自动发邮件不错哦,美女程序猿web.xml文件 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <servlet-name>...

    Java The Complete Reference ,11th Edition.pdf

    Fully updated for Java SE 11, Java: The Complete Reference, Eleventh Edition explains how to develop, compile, debug, and run Java programs. Best-selling programming author Herb Schildt covers the ...

    Core Java Volume I 最新第8版 全两卷 (附随书源码)

    Fully updated for the new Java SE 6 platform, this no-nonsense tutorial and reliable reference illuminates the most important language and library features with thoroughly tested real-world examples....

    java api最新7.0

    本文档是 Java Platform Standard Edition 7 的 API !Java 1.7 API的中文帮助文档。 深圳电信培训中心 徐海蛟博士教学用api 7.0中文文档。支持全文检索,在线即时查询。 里面列出了Java jdk 1.7的所有类及其使用...

    《Pearson.Java.How.To.Program.late.objects.version.10th.Edition》 高清完整英文PDF版

    Keep Your Course Current: This edition can be used with Java SE 7 or Java SE 8, and is up-to-date with the latest technologies and advancements. Facilitate Learning with Outstanding Applied Pedagogy: ...

    Core Java Volume II 最新第8版 part2全两卷 (附随书源码)

    Fully updated for the new Java SE 6 platform, this no-nonsense tutorial and reliable reference illuminates the most important language and library features with thoroughly tested real-world examples....

    JavaAPI1.6中文chm文档 part1

    java.awt.im.spi 提供启用可以与 Java 运行时环境一起使用的输入方法开发的接口。 java.awt.image 提供创建和修改图像的各种类。 java.awt.image.renderable 提供用于生成与呈现无关的图像的类和接口。 java.awt....

    (java se 代码)Bank Account Management System 银行账户管理子系统

    ATM 7:Swing GUI开发 第一步部分:为ATM项目添加用户客户端操作界面 需要以下几个类: 1) ATMClient: 其中会包含一个Frame,这是用户主界面. 2) MainPanel:主界面,用户可以选择开户或者登录 3) RegisterPanel:用户...

    Core Java Volume I-Fundamentals(PrenticeHall,2016)

    Now, Core Java®, Volume I—Fundamentals, Tenth Edition, has been extensively updated to reflect the most eagerly awaited and innovative version of Java in years: Java SE 8. Rewritten and reorganized...

    自己用java制作贪吃蛇小游戏

    catch(Exception e){ break; } if(!paused){ if (moveOn()){ gs.repaint(); } else{ JOptionPane.showMessageDialog( null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; ...

    JavaAPI中文chm文档 part2

    java.awt.im.spi 提供启用可以与 Java 运行时环境一起使用的输入方法开发的接口。 java.awt.image 提供创建和修改图像的各种类。 java.awt.image.renderable 提供用于生成与呈现无关的图像的类和接口。 java.awt....

    javacv-platform-1.3.3-src

    An implementation of Java SE 7 or newer: OpenJDK http://openjdk.java.net/install/ or Sun JDK http://www.oracle.com/technetwork/java/javase/downloads/ or IBM JDK ...

Global site tag (gtag.js) - Google Analytics