首页 > 编程语言 >java 7中再谈try catch

java 7中再谈try catch

时间:2022-12-05 13:01:59浏览次数:52  
标签:Exception java NewResource try res catch new closing public


java 7中的try catch除了之前谈到的新特性外,本文简单来例子小结下,其实还是有不少地方要注意的,首先看一个典型的代码:

先来两个异常类:


1. public class ExceptionA extends
2. public
3. super(message);
4. }
5. }
6. public class ExceptionB extends
7. public
8. super(message);
9. }
10. }


public class ExceptionA extends Exception{
public ExceptionA(String message){
super(message);
}
}
public class ExceptionB extends Exception{
public ExceptionB(String message){
super(message);
}
}


再创建一个资源类oldresource,如下:


1.   
2. public class
3. public void doSomeWork(String work) throws
4. "Doing: "+work);
5. throw new ExceptionA("Exception occured while doing work");
6. }
7. public void close() throws
8. "Closing the resource");
9. throw new ExceptionB("Exception occured while closing");
10. }
11. }

public class OldResource{
public void doSomeWork(String work) throws ExceptionA{
System.out.println("Doing: "+work);
throw new ExceptionA("Exception occured while doing work");
}
public void close() throws ExceptionB{
System.out.println("Closing the resource");
throw new ExceptionB("Exception occured while closing");
}
}
public class OldResource{
public void doSomeWork(String work) throws ExceptionA{
System.out.println("Doing: "+work);
throw new ExceptionA("Exception occured while doing work");
}
public void close() throws ExceptionB{
System.out.println("Closing the resource");
throw new ExceptionB("Exception occured while closing");
}
}



我们开始使用之:


    1. public class
    2. public static void
    3. null;
    4. try
    5. new
    6. "Writing an article");
    7. catch
    8. "Exception Message: "+
    9. " Exception Type: "+e.getClass().getName());
    10. finally{
    11. try
    12. res.close();
    13. catch
    14. "Exception Message: "+
    15. " Exception Type: "+e.getClass().getName());
    16. }
    17. }
    18. }
    19. }

    public class OldTry {
    public static void main(String[] args) {
    OldResource res = null;
    try {
    res = new OldResource();
    res.doSomeWork("Writing an article");
    } catch (Exception e) {
    System.out.println("Exception Message: "+
    e.getMessage()+" Exception Type: "+e.getClass().getName());
    } finally{
    try {
    res.close();
    } catch (Exception e) {
    System.out.println("Exception Message: "+
    e.getMessage()+" Exception Type: "+e.getClass().getName());
    }
    }
    }
    }
    public class OldTry {
    public static void main(String[] args) {
    OldResource res = null;
    try {
    res = new OldResource();
    res.doSomeWork("Writing an article");
    } catch (Exception e) {
    System.out.println("Exception Message: "+
    e.getMessage()+" Exception Type: "+e.getClass().getName());
    } finally{
    try {
    res.close();
    } catch (Exception e) {
    System.out.println("Exception Message: "+
    e.getMessage()+" Exception Type: "+e.getClass().getName());
    }
    }
    }
    }



    看输出:


       Doing: Writing an article


    Exception Message: Exception occured while doing work Exception Type: javaapplication4.ExceptionA


    Closing the resource


    Exception Message: Exception occured while closing Exception Type: javaapplication4.ExceptionB



    再来看java 7中的新写法,代码如下:


    1. public class NewResource implements
    2. String closingMessage;
    3.
    4. public
    5. this.closingMessage = closingMessage;
    6. }
    7.
    8. public void doSomeWork(String work) throws
    9. System.out.println(work);
    10. throw new ExceptionA("Exception thrown while doing some work");
    11. }
    12. public void close() throws
    13. System.out.println(closingMessage);
    14. throw new ExceptionB("Exception thrown while closing");
    15. }
    16.
    17. public void doSomeWork(NewResource res) throws
    18. "Wow res getting res to do work");
    19. }
    20. }

    public class NewResource implements AutoCloseable{
    String closingMessage;

    public NewResource(String closingMessage) {
    this.closingMessage = closingMessage;
    }

    public void doSomeWork(String work) throws ExceptionA{
    System.out.println(work);
    throw new ExceptionA("Exception thrown while doing some work");
    }
    public void close() throws ExceptionB{
    System.out.println(closingMessage);
    throw new ExceptionB("Exception thrown while closing");
    }

    public void doSomeWork(NewResource res) throws ExceptionA{
    res.doSomeWork("Wow res getting res to do work");
    }
    }



      在JAVA 7中,要自动在try catch中利用到新特性,想不写那么多东西就关闭资源,则可以编写实现 AutoCloseable类的,则都可以利用该特性了。


    在主程序中调用:


     


    1. public class
    2. public static void
    3. try(NewResource res = new NewResource("Res1 closing")){
    4. "Listening to podcast");
    5. catch(Exception e){
    6. "Exception: "+
    7. " Thrown by: "+e.getClass().getSimpleName());
    8. }
    9. }
    10. }


    public class TryWithRes {
    public static void main(String[] args) {
    try(NewResource res = new NewResource("Res1 closing")){
    res.doSomeWork("Listening to podcast");
    } catch(Exception e){
    System.out.println("Exception: "+
    e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());
    }
    }
    }



    输出结果为:


      Listening to podcast


    Res1 closing


    Exception: Exception thrown while doing some work Thrown by: ExceptionA



    大家可以思考下为什么这样输出,在新特性中,资源的自动关闭调用了close(),而


    NewResource res = new NewResource("Res1 closing")){


    已经为closingMessage赋值了,而最后的Exception e是输出了,suprred掉了


    exception a和exception b的输出。



    再看一个多层嵌套的try catch例子


     

    1. public class
    2. public static void
    3. try(NewResource res = new NewResource("Res1 closing");
    4. new NewResource("Res2 closing")){
    5. try(NewResource nestedRes = new NewResource("Nestedres closing")){
    6. nestedRes.doSomeWork(res2);
    7. }
    8. catch(Exception e){
    9. "Exception: "+
    10. " Thrown by: "+e.getClass().getSimpleName());
    11. }
    12.
    13. }
    14. }

    public class TryWithRes {
    public static void main(String[] args) {
    try(NewResource res = new NewResource("Res1 closing");
    NewResource res2 = new NewResource("Res2 closing")){
    try(NewResource nestedRes = new NewResource("Nestedres closing")){
    nestedRes.doSomeWork(res2);
    }
    } catch(Exception e){
    System.out.println("Exception: "+
    e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());
    }

    }
    }


    输出:


      Wow res getting res to do work


    Nestedres closing


    Res2 closing


    Res1 closing


    Exception: Exception thrown while doing some work Thrown by: ExceptionA



    可以看到,后声明的资源上被最先CLOSE掉的,这里各自原先的exception都被supressed掉了。还可以用e.getSuppressed() 把屏蔽掉的exception都放来,比如




    1. public class
    2. public static void
    3. try(NewResource res = new NewResource("Res1 closing");
    4. new NewResource("Res2 closing")){
    5. try(NewResource nestedRes = new NewResource("Nestedres closing")){
    6. nestedRes.doSomeWork(res2);
    7. }
    8. catch(Exception e){
    9. "Exception: "+
    10. " Thrown by: "+e.getClass().getSimpleName());
    11. if (e.getSuppressed() != null){
    12. for
    13. System.out.println(t.getMessage()+
    14. " Class: "+t.getClass().getSimpleName());
    15. }
    16. }
    17. }
    18.
    19. }
    20. }

    public class TryWithRes {
    public static void main(String[] args) {
    try(NewResource res = new NewResource("Res1 closing");
    NewResource res2 = new NewResource("Res2 closing")){
    try(NewResource nestedRes = new NewResource("Nestedres closing")){
    nestedRes.doSomeWork(res2);
    }
    } catch(Exception e){
    System.out.println("Exception: "+
    e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());
    if (e.getSuppressed() != null){
    for (Throwable t : e.getSuppressed()){
    System.out.println(t.getMessage()+
    " Class: "+t.getClass().getSimpleName());
    }
    }
    }

    }
    }

    输出显示:


    Wow res getting res to do work


    Nestedres closing


    Res2 closing


    Res1 closing


    Exception: Exception thrown while doing some work Thrown by: ExceptionA


    Exception thrown while closing Class: ExceptionB


    Exception thrown while closing Class: ExceptionB


    Exception thrown while closing Class: ExceptionB



    标签:Exception,java,NewResource,try,res,catch,new,closing,public
    From: https://blog.51cto.com/u_14230175/5911933

    相关文章

    • java中对象存在形式
      本文主要讲述jvm中对象的存储形式:classCat{Stringname;intage;Stringcolor;//行为}依据Cat类创建对象publicclassObject01......
    • JAVASCRIPT数组小结
      ​数组是值的有序集合。每个值叫做一个元素,而每个元素在数组中有一个位置,以数字表示,称为索引。JavaScript数组是无类型的,数组元素可以是任意类型,并......
    • 在c#中调用c++的dll崩溃了,try catch 怎么获取异常?
      在framework框架下,通过添加HandleProcessCorruptedStateExceptionsAttribute属性来解决这个问题,(.netcore1.0到3.1之前,不支持从损坏的进程状态异常中恢复,即trycatch没有......
    • 笔记:正确得使用java 8得optional
      publicstaticStringgetName(Useru){if(u==null)return"Unknown";returnu.name;}比如以前这样得代码,经常要判断是否NULL,很麻烦,有了java8得option......
    • JDK的dt.jar和Java BeanInfo接口
      在JAVA_HOME/lib下面有两个比较重要的jar文件,tools.jar和dt.jar。 tools.jar在上篇文章中做了简单的介绍。这里来介绍下dt.jar。在Oracle官方网站搜dt.jar,找到JDKand......
    • (笔记)JMH基准测试,不错的JAVA基准测试工具
      测试JAVA中的方法的执行性能,比较稳妥合理的方法,是用JMH(​​https://openjdk.java.net/projects/code-tools/jmh/​​)这个JAVA的测试工具。1)MAVEN加入库: <properties>......
    • 快速比较JAVA中两个集合是否相等
      有几个方法:1)如果是不在乎顺序,只要内容相同就可以认为相等,则:public<TextendsComparable<T>>booleanisEquals(List<T>list1,List<T>list2){if(list1==nul......
    • Java同步器之ReentrantLock源码分析(一)
      一、概述ReentrantLock是Java并发包中提供的一个可重入的互斥锁。ReentrantLock和synchronized在基本用法,行为语义上都是类似的,同样都具有可重入性。只不过相比原生的Sync......
    • 两道面试题,带你解析Java类加载机制
      在许多Java面试中,我们经常会看到关于Java类加载机制的考察,例如下面这道题:classGrandpa{static{System.out.println("爷爷在静态代码块");}}classFatherextendsGra......
    • JAVA 解压缩代码写法
      packagecom.chinaunicom.asset.common.utils.compress;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.compress.archivers.ArchiveEntry;importorg.......