Try catch again in Java 7

Source: Internet
Author: User

In addition to the new features mentioned above, try catch in Java 7 is a simple example in this article. In fact, there are still many points to note. First, let's look at a typical code:

Two exception classes are introduced:

 

Java code
  1. Public class extends tiona extends exception {
  2. Public regiontiona (string message ){
  3. Super (Message );
  4. }
  5. }
  6. Public class exceptionb extends exception {
  7. Public exceptionb (string message ){
  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);    }}

Create another resource class oldresource, as shown below: Java code

  1. Public class oldresource {
  2. Public void dosomework (string work) throws javastiona {
  3. System. Out. println ("doing:" + work );
  4. Throw new effectiona ("exception occured while doing work ");
  5. }
  6. Public void close () throws exceptionb {
  7. System. Out. println ("Closing the resource ");
  8. Throw new exceptionb ("exception occured while closing ");
  9. }
  10. }
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");    }}

Let's start using: Java code

  1. Public class oldtry {
  2. Public static void main (string [] ARGs ){
  3. Oldresource res = NULL;
  4. Try {
  5. Res = new oldresource ();
  6. Res. dosomework ("writing an article ");
  7. } Catch (exception e ){
  8. System. Out. println ("exception message:" +
  9. E. getmessage () + "exception type:" + E. getclass (). getname ());
  10. } Finally {
  11. Try {
  12. Res. Close ();
  13. } Catch (exception e ){
  14. System. Out. println ("exception message:" +
  15. E. getmessage () + "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());            }        }    }}

View output:
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

Let's take a look at the new writing method in Java 7. The Code is as follows: Java code

  1. Public class newresource implements autocloseable {
  2. String closingmessage;
  3. Public newresource (string closingmessage ){
  4. This. closingmessage = closingmessage;
  5. }
  6. Public void dosomework (string work) throws javastiona {
  7. System. Out. println (work );
  8. Throw new partition tiona ("exception thrown while doing some work ");
  9. }
  10. Public void close () throws exceptionb {
  11. System. Out. println (closingmessage );
  12. Throw new exceptionb ("exception thrown while closing ");
  13. }
  14. Public void dosomework (newresource res) throws writable tiona {
  15. Res. dosomework ("Wow res getting res to do work ");
  16. }
  17. }
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");    }}

In Java 7, new features must be automatically used in try catch. If you want to disable resources without writing so many things, you can compile and implement the autocloseable class, and you can use this feature.

Call in the main program:
 

Java code
  1. Public class trywithres {
  2. Public static void main (string [] ARGs ){
  3. Try (newresource res = new newresource ("RES1 closing ")){
  4. Res. dosomework ("Listening to podcast ");
  5. } Catch (exception e ){
  6. System. Out. println ("exception:" +
  7. E. getmessage () + "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());        }    }}

Output result:
Listening to podcast
RES1 closing
Exception: exception thrown while doing some work thrown by: interval tiona

You can think about the reason for this output. In the new feature, close () is called automatically when the resource is closed.
Newresource res = new newresource ("RES1 closing ")){
The value of closingmessage has been assigned, and the final exception e is output, and suprred is dropped.
Output of exception A and exception B.

Let's look at a multi-layer nested try catch example.
 

Java code
  1. Public class trywithres {
  2. Public static void main (string [] ARGs ){
  3. Try (newresource res = new newresource ("RES1 closing ");
  4. Newresource RES2 = new newresource ("RES2 closing ")){
  5. Try (newresource nestedres = new newresource ("nestedres closing ")){
  6. Nestedres. dosomework (RES2 );
  7. }
  8. } Catch (exception e ){
  9. System. Out. println ("exception:" +
  10. E. getmessage () + "thrown by:" + E. getclass (). getsimplename ());
  11. }
  12. }
  13. }
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());        }     }}

Output:
Wow res getting res to do work
Nestedres closing
RES2 closing
RES1 closing
Exception: exception thrown while doing some work thrown by: interval tiona

We can see that the declared resources are closed first, and the previous exceptions are all supressed. You can also use E. getsuppressed () to put all the blocked exceptions, for example
Java code

  1. Public class trywithres {
  2. Public static void main (string [] ARGs ){
  3. Try (newresource res = new newresource ("RES1 closing ");
  4. Newresource RES2 = new newresource ("RES2 closing ")){
  5. Try (newresource nestedres = new newresource ("nestedres closing ")){
  6. Nestedres. dosomework (RES2 );
  7. }
  8. } Catch (exception e ){
  9. System. Out. println ("exception:" +
  10. E. getmessage () + "thrown by:" + E. getclass (). getsimplename ());
  11. If (E. getsuppressed ()! = NULL ){
  12. For (throwable T: E. getsuppressed ()){
  13. System. Out. println (T. getmessage () +
  14. "Class:" + T. getclass (). getsimplename ());
  15. }
  16. }
  17. }
  18. }
  19. }
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());                }            }        }     }}

Output:
Wow res getting res to do work
Nestedres closing
RES2 closing
RES1 closing
Exception: exception thrown while doing some work thrown by: interval tiona
Exception thrown while closing class: exceptionb
Exception thrown while closing class: exceptionb
Exception thrown while closing class: exceptionb

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.