A brief talk on Java exception handling (Try Catch Finally) _java

Source: Internet
Author: User
Tags exception handling stack trace throw exception throwable try catch

The unusual English word is exception, the literal translation is "The accident, the exception" The meaning, is also abnormal condition. In fact, exceptions are essentially procedural errors, including program logic errors and system errors.

A preface

Java exception handling is not unfamiliar to everyone, generally have the following two points:

1. Throw Exception: Throw exception

Class simpleexception{public
  void A () throws exception{
    throw new Exception ();
  }

2. Catch Exceptions:

public class MyException {public
  static void Main (string[] args) {
    myexception e = new MyException ();
    Simpleexception se = new simpleexception ();
    try {
      se.a ();
    } catch (Exception E1) {
      e1.printstacktrace ();

}}} Class simpleexception{public
  void A () throws exception{
    throw new Exception ();
}

This article will be based on this, a more in-depth discussion of a number of details.

Two custom exception classes

The Java language provides us with a lot of exception classes, but sometimes we have to customize them to create the exception class for the convenience of writing code:

Class Simpleexception extends Exception {};
Once created, we can use a try catch to catch it:

public class MyException {public
  static void Main (string[] args) {
    myexception e = new MyException ();
    try {
      e.a ();
    } catch (Simpleexception E1) {
      e1.printstacktrace ();
    }
  }
  
  public void A () throws simpleexception{
    throw new Simpleexception ();
  }

Class Simpleexception extends Exception {};

We defined a method a () in myexception to throw the simpleexception exception, and then we called the method in Main () and caught the exception using a try catch:

Simpleexception at
  Myexception.a (myexception.java:15) at
  myexception.main (myexception.java:8)
  at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) at
  Sun.reflect.NativeMethodAccessorImpl.invoke ( nativemethodaccessorimpl.java:57) at
  Sun.reflect.DelegatingMethodAccessorImpl.invoke ( delegatingmethodaccessorimpl.java:43) at
  Java.lang.reflect.Method.invoke (method.java:606)
  at Com.intellij.rt.execution.application.AppMain.main (appmain.java:144)

Process finished with exit code 0


After compiling the results, mainly look at the first three lines on the line. Here are some highlights:
1. Throws the exception type the designation: (Exception specification)
When we need to throw an exception in a method, we use throw to add an instance of an exception class, where the program throws the corresponding exception to the client program (the program that calls the code) and exits here (equivalent to return). Also note that we must specify the exception type when defining the method, such as the following code throws a Simpleexception exception

public void A () throws Simpleexception

2. Throw multiple Exceptions:

  public void A () throws simpleexception,aexception,bexception{
    throw new Simpleexception ();
    
  }

Different exception classes are separated by commas, in which case we do not have to throw an instance of each exception class (), but the client code must catch to each exception class:

public class MyException {public
  static void Main (string[] args) {
    myexception e = new MyException ();
    try {
      e.a ();
    } catch (Simpleexception E1) {
      e1.printstacktrace ();
    } catch (Bexception E1) {
      E1.printstacktrace ();
    } catch (Aexception E1) {
      e1.printstacktrace ();
    }
  }

  public void A () throws simpleexception,aexception,bexception{
    throw new Simpleexception ();
    
  }

Class Simpleexception extends Exception {};
Class Aexception extends exception{}
class Bexception extends exception{}


Three stack trace

Whether you throw an exception or catch a handle exception, our goal is to write a more robust program, which relies heavily on the exception information that the Java exception mechanism gives us, and its carrier is stack trace.
In the previous code we used Printstacktrace () to print out the exception information, but we can also use the Getstacktrace () method to get the Stacktraceelement type collection, if you have idea at hand, You can first search out the Stacktraceelement class, you can find that it implements the interface serializable, and then look at its class description:

/**
 * An element in a stack trace, as returned by {@link
 * throwable#getstacktrace ()}. Each element is represents a single stack frame.
 * All stack frames except for the "one" in the top of the stack represent
 * a method invocation. The frame at the top of the stack represents the
 "* Execution point" at which the stack trace is generated. Typically, * This is the
 "point" at which the throwable corresponding to the stack trace * was
 created.
 *
 @since 1.4
 * @author Josh Bloch *
 *

It is clear that each instance of this class is an element of stack trace that represents a stack Frame,stack trace is returned by the Getstacktrace () method. After I tried to translate a few times, all feel bad, or directly on the code can be said clearly:

public class MyException {public
  static void Main (string[] args) {
    myexception e = new MyException ();
    E.a ();

  public void A () {
    try {
      throw new Exception ();
    } catch (Exception e) {
      stacktraceelement[] ste = E.getstack Trace ();
      System.out.println (Ste.length);}}


We define method A, let it throw the exception exception and capture it, then we get an array of stacktraceelement types through the Getstacktrace () method, and print the length of the arrays:

7

Process finished with exit code 0
Let's change the code a little bit and not catch the exception in a, we redefine a method B so that it catches the exception while calling a:

public class MyException {public
  static void Main (string[] args) {
    myexception e = new MyException ();
    E.b ();
  }

  public void B () {
    try {
      a ()
    } catch (Exception e) {
      stacktraceelement[] ste = E.getstacktrace ();
      System.out.println (ste.length);
    }

  public void A () throws exception{
    throw new Exception ();
  }


The results are as follows:

8

Process finished with exit code 0
Don't worry, let's take a look at something interesting:

public class MyException {public
  static void Main (string[] args) {
    MyException exception = new MyException (); 
   
    try {
      exception.c ();
    } catch (Exception e) {
      stacktraceelement[] ste = E.getstacktrace ();
      System.out.println (ste.length);
      System.out.println ("---------------------------------------------------------------");
      For (Stacktraceelement s:e.getstacktrace ()) {
        System.out.println (s.getclassname () + ': Method ' +s.getmethodname ( + "at line" +s.getlinenumber ());
      }
      System.out.println ("---------------------------------------------------------------");

    }

 public void C () throws exception{
    try {
      a ();
    } catch (Exception e) {
      throw e;
    }
  }

  public void A () throws exception{
    throw new Exception ();
  }



   

Here is the result:

8
---------------------------------------------------------------
myexception:method A at line43
Myexception:method C at Line39
Myexception:method main at Line9
Sun.reflect.NativeMethodAccessorImpl:method Invoke0 at Line-2
Sun.reflect.NativeMethodAccessorImpl:method invoke at Line57
Sun.reflect.DelegatingMethodAccessorImpl:method invoke at Line43
Java.lang.reflect.Method:method invoke at line606
Com.intellij.rt.execution.application.AppMain:method Main at line144
--------------------------- ------------------------------------

Process finished with exit code 0

In other words, getstacktrace () returns a stack that contains some basic information from the caller (main ()) to the original thrown exception (a ()), in which we catch the exception and throw it back through the throws when we call the A method in the C method (rethrow , the method of invoking the C method can catch and handle the exception, or you can choose to continue throwing the higher-level caller (near the bottom of the stack) to handle it. Rethrow Although very convenient, but there are some problems, we look at the following code:

public class MyException {public
  static void Main (string[] args) {
    MyException exception = new MyException (); 
   
    try {
      exception.c ();
    } catch (Exception e) {
      e.printstacktrace (System.out);
    }

  }

  public void C () throws exception{
    try {
      a ();
    } catch (Exception e) {
      throw e;
    }
  }

  public void A () throws exception{

    throw the new Exception ("Exception from A ()")
  ;
}
Java.lang.Exception:Exception from A () in
  Myexception.a (myexception.java:40) at
  myexception.c ( myexception.java:30) at
  Myexception.main (myexception.java:21)


   

We're going to throw e back in C, print it out in main with E.printstacktrace (), and we can see that the print stack trace or a, if we want to turn stack trace into C, we can write this:

public class MyException {public
  static void Main (string[] args) {
    MyException exception = new MyException (); 
   
    try {
      exception.c ();
    } catch (Exception e) {
      e.printstacktrace (System.out);
    }

  }

  public void C () throws exception{
    try {
      a ();
    } catch (Exception e) {
//      throw E;
      Throw (Exception) e.fillinstacktrace ();
    }

  public void A () throws exception{

    throw the new Exception ("Exception from A ()")
  ;
}
Java.lang.Exception:Exception from A () in
  myexception.c (myexception.java:22) at
  Myexception.main ( MYEXCEPTION.JAVA:10)



   

Four abnormal chain Exception chaining

Let's take a look at a scene:

 public class TestException {public static void main (string[] args) {testexception
    TestException = new TestException ();
    try {testexception.c ();
    catch (CException e) {e.printstacktrace ();
    } public void A () throws aexception{aexception aexception = new Aexception ("This is a exception");
  Throw aexception;
    public void B () throws bexception{try {a ();
    catch (Aexception e) {throw new Bexception ("This is b exception");
    } public void C () throws cexception{try {B ();
    catch (Bexception e) {throw new CException ("This is C exception");
  Class Aexception extends exception{public aexception (String msg) {super (MSG);
  Class Bexception extends exception{public bexception (String msg) {super (MSG);
  Class CException extends exception{public cexception (String msg) {super (MSG); }
}

Created three exception classes aexception, Bexception, CException, then throws Aexception in a (), captures aexception in B (), and throws Bexception, finally in C () To capture Bexception and throw cexception, the results are printed as follows:

Cexception:this is c exception at
  testexception.c (testexception.java:31) at
  Testexception.main ( TESTEXCEPTION.JAVA:8)

OK, we only see cexception information, aexception,bexception exception information has been lost, this time the function of the abnormal chain came out, look at the code:

public class TestException {public static void main (string[] args) {testexception testexception = new Testexceptio
    N ();
    try {testexception.c ();
    catch (CException e) {e.printstacktrace ();
    } public void A () throws aexception{aexception aexception = new Aexception ("This is a exception");
  Throw aexception;
    public void B () throws bexception{try {a ();
      catch (Aexception e) {//throw new Bexception ("This is b exception");
      Bexception bexception = new Bexception ("This is b exception");
      Bexception.initcause (e);
    Throw bexception;
    } public void C () throws cexception{try {B ();
      catch (Bexception e) {//throw new CException ("This is C exception");
      CException CException = new CException ("This is C exception");
      Cexception.initcause (e);
    Throw CException;
  Class Aexception extends exception{public aexception (String msg) {super (MSG); }
Class Bexception extends exception{public bexception (String msg) {super (MSG);
  Class CException extends exception{public cexception (String msg) {super (MSG);

 }
}

We use the Initcause () method to concatenate the exception information, and the result is as follows:

Cexception:this is c exception at
  testexception.c (testexception.java:35) at
  Testexception.main ( Testexception.java:8) at
  sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method)
  at Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:57) at
  Sun.reflect.DelegatingMethodAccessorImpl.invoke (delegatingmethodaccessorimpl.java:43) at
  Java.lang.reflect.Method.invoke (method.java:606) at
  Com.intellij.rt.execution.application.AppMain.main ( appmain.java:144)
caused By:BException:this is b exception at
  testexception.b (testexception.java:24)
  At TESTEXCEPTION.C (testexception.java:32) ...
  6 more
caused by:AException:this are a exception at
  Testexception.a (testexception.java:15)
  at TESTEXCEPTION.B (testexception.java:21) ...
  7 more

Process finished with exit code 0


Five PostScript

In fact, there are a lot of Java exception processing need to explore the place, but because I have limited experience, can not feel too deep, the most commonly used is

try {
      ...
    } catch (Exception e) {
      ... 
    } finally {
     ///regardless of whether the exception will be captured or handled, such as shutting down IO operations 
    }

But anyway, we want to thank Java for providing us with the exception mechanism, it is like an elderly, and occasionally to guide us to the road, but also let us in the code when not so boring:

Related Article

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.