`

java 7中再谈try catch

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


先来两个异常类:

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



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

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 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中的新写法,代码如下:
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类的,则都可以利用该特性了。
在主程序中调用:
 
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例子
 
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都放来,比如
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

3
2
分享到:
评论

相关推荐

    java try…catch嵌套捕获异常的实例

    在`CatchException_03.java`这个文件中,可能包含了实际的嵌套`try-catch`异常处理代码实例。配合`Java.jpg`可能是一个解释或演示这些概念的图片。为了深入理解,你应该阅读和分析这个源代码文件,并结合图片中的...

    java中try catch的用法

    ### Java中try-catch的用法详解 #### 一、基本概念 在Java编程语言中,`try-catch`结构是一种用于处理程序运行时可能出现的异常情况的重要机制。通过使用`try-catch`块,开发者可以更加精细地控制程序的行为,并...

    java try…catch捕获异常的实例

    总的来说,`try-catch`机制是Java中异常处理的核心,它提供了对程序运行时错误的优雅处理方式,帮助开发者编写更加健壮的代码。通过合理地使用`try-catch`,我们可以确保程序在遇到问题时不会无端崩溃,而是能够适当...

    try_catch_finally异常处理java

    本文将深入探讨Java中的`try-catch-finally`语句块,以及它们在异常处理中的作用。 首先,`try`块是异常处理的起点。在这个代码段中,我们通常会放置可能会抛出异常的代码。当Java执行到可能抛出异常的代码行时,...

    19.java嵌套的try…catch语句.zip

    19.java嵌套的try…catch语句.zip19.java嵌套的try…catch语句.zip19.java嵌套的try…catch语句.zip19.java嵌套的try…catch语句.zip19.java嵌套的try…catch语句.zip19.java嵌套的try…catch语句.zip19.java嵌套的...

    Springboot全局异常捕获及try catch区别解析

    当代码执行到try语句块中时,如果出现了异常,Java虚拟机会将其捕获并抛出到catch子句中,在catch子句中可以进行异常处理和错误信息的返回。try catch语句可以捕获到各种类型的异常,包括运行时异常和检查异常。 而...

    trycatch.zip

    本示例中的"trycatch.zip"文件内容就是展示了如何在Golang中模拟`try...catch`和`try...catch...finally`。 Golang的核心错误处理方式是通过返回错误值。通常,函数会返回一个错误值,如果在执行过程中遇到问题,就...

    17.javatry…catch…finally语句.zip

    17.javatry…catch…finally语句.zip17.javatry…catch…finally语句.zip17.javatry…catch…finally语句.zip17.javatry…catch…finally语句.zip17.javatry…catch…finally语句.zip17.javatry…catch…finally语句...

    try 与 catch finally关键字

    Java的 try 与 catch finally关键字的使用

    try-catch的用法和含义

    `try-catch` 结构作为异常处理的核心机制,在各种编程语言中广泛采用,如 Java、C# 和 JavaScript 等。本文将深入探讨 `try-catch` 的基本概念、语法结构及其应用场景。 #### 一、`try-catch` 的基本概念 `try-...

    使用try-catch-finally处理异常

    Java、C#等许多编程语言提供了异常处理框架,其中“try-catch-finally”是常用的一种结构。下面我们将详细探讨这个主题。 1. **异常的概念** 异常是程序执行期间发生的非正常情况,它可能由用户输入错误、文件不...

    java基础知识-try-catch的使用

    try块中包含可能会产生异常的代码,当try块内的代码发生异常时,程序会立即跳转到与异常类型相匹配的catch块进行处理。 在catch块中,你可以编写适当的处理逻辑来处理特定类型的异常。每个catch块可以捕获不同类型...

    java try…catch…finally捕获异常的实例

    总结来说,`try-catch-finally`结构是Java中处理异常的关键工具,它允许开发者优雅地处理错误,保持程序的健壮性,同时确保必要的清理工作得以执行。通过正确使用这些结构,可以提高代码的可读性和可维护性。

    Java try catch finally异常处理组合详解

    Java try catch finally异常处理组합是Java语言中的异常处理机制,用于捕获和处理程序中的异常。下面对try catch finally异常处理组合进行详细的介绍。 try catch组合: try catch组合是Java中最基本的异常处理...

    try~catch~finally中关于return的问题

    在Java的异常机制中,如果finally中含有return语句,则try和catch中的return语句将会被JVM忽视

    Java异常处理机制try catch流程详解

    Java 异常处理机制的核心是 try...catch 语句结构,通过 try 语句块中的代码可能会抛出异常,而 catch 语句块则负责捕获和处理这些异常。try 语句块中可以包含多个 catch 语句块,每个 catch 语句块可以捕获不同类型...

    Java中异常处理之try和catch代码块的使用

    Java提供了结构化的异常处理机制,其中包括`try`和`catch`代码块,使得程序员可以优雅地处理这些异常,而不必让程序完全崩溃。 `try`代码块是用于包围可能会抛出异常的代码的结构。当`try`块中的代码触发了一个异常...

    Java中try、catch的使用方法

    "Java中try、catch的使用方法" 本文主要介绍了Java中try、catch的使用方法,通过实例代码详细地介绍了try、catch的使用方法,对大家的学习或工作具有一定的参考借鉴价值。 try-catch语句的语法格式为:try{ //代码...

    try-catch-finally捕获异常

    try-catch-finally语句是Java语言中一种常用的异常处理机制,当程序在执行过程中出现异常时,可以使用try-catch-finally语句来捕获和处理异常。下面将详细介绍try-catch-finally语句的使用方法和注意事项。 一、try...

    java中throws与try...catch的区别点

    Java中的throws与try...catch的区别点 Java是面向对象的编程语言,它提供了强大的异常处理机制,帮助开发者更好地处理程序中的错误和异常。其中,throws和try...catch是Java中两种常用的异常处理方式,本文将对这两...

Global site tag (gtag.js) - Google Analytics