Java exception handling Instance analysis _java

Source: Internet
Author: User
Tags exception handling finally block

This example describes the use of Java exception handling. Share to everyone for your reference. The specific analysis is as follows:

Java's exception handling mechanism can help us avoid or handle the possible errors of the program, so that the program in the face of some recoverable errors will not terminate unexpectedly, but to deal with these errors, but also to write a program when we do not have to write a large number of code to check the error situation, Enhances the readability and logic of the code. In Java, an exception represents an incorrect entity object.

Exceptions can be divided into two categories: a serious error, such as hardware errors, low memory, and so on, they correspond to the Java.lang package of the error class and its subclasses. Usually this type of error program cannot be recovered by itself, need to interrupt the execution of the program, the other is not a serious error, such as the user entered illegal data, by 0 and so on, they correspond to the Java.lang package exception class and its subclasses, this error can generally be restored, does not affect the operation of the program.
We can use the try, catch,finally keyword to catch the exception.

1, try, catch

Place the statement that may have an exception in the try{} block and capture it in the catch{} statement block. If the exception is removed by 0:

public class Simpledemo 
{ 
  //Division operations public 
  Static int devision (int a,int b) 
  { 
    return 
   
  /A/A;} public static void Main (string[] args) 
  { 
    try  
    { 
      //5 divided by 0 
      simpledemo.devision (5,0); 
      System.out.println ("Exception"); 
    }  
    catch (Exception e)  
    { 
      e.printstacktrace (); 
    } 
     
    System.out.println ("Finish"); 
  } 

Execution results:

As you can see, finish is printed, stating that the program is not terminated because of an error that has been removed by 0.
We also found that the SYSTEM.OUT.PRINTLN statement below the Simpledemo.devision () of the exception was not executed. Once an exception occurs, the program jumps out of the current execution position without executing the statement following the exception.

2, finally

The statement in the finally statement block is executed regardless of whether an exception occurred or not.
One might ask, since the statement in a finally block is executed regardless of whether the exception occurred, what is the real effect of this finally? I don't have to finally write it right outside, okay?
As in the previous example, we add a return in the Catch statement block:

public class Simpledemo 
{ 
  //Division operations Public 
  Static INT division (int A,int b) 
  { 
    return 
  /A/A;} public static void Main (string[] args) 
  { 
    try  
    { 
      //5 divided by 0 
      simpledemo.division (5,0); 
      System.out.println ("Exception"); 
    }  
    catch (Exception e)  
    { 
      e.printstacktrace (); 
      Return The main function returns 
    } 
    finally 
    { 
      System.out.println ("finally"); 
    } 
    System.out.println ("Finish"); 
  } 

At this time, finally the outside finish was not printed, and finally the inside finally block was printed out.

Finally, it is very useful in actual development. For example, if we open a database and have an exception when the database reads and writes data, then we should close the database connection and release the appropriate resources. This is the most appropriate time to write code that frees up resources in the finally block.

Note, however, that finally blocks are not executed in one case. If a program exits before it executes to a finally block, such as invoking the System.exit () method, the finally block is not given the opportunity to execute.

3, throw out the exception

If there is an exception in a method, but we do not want to handle the exception directly in the method, but want the caller of the method to handle it, you can use the throws keyword to declare the method to throw out the exception. This is very common in the API functions that sun gives us, such as the Read method in Java.io.Reader is declared to throw a IOException exception:

public int read (char[] cbuf)
     throws IOException

When we call the Read method we must place it in the TRY statement block for exception capture, otherwise the compiler will complain, forcing us to catch the exception.
Of course, if we really don't want to handle the exception when we call read, we can also declare the method that calls the Read method as throws IOException, so that the exception is thrown out again. If we declare a exception exception in the main function, then the exception information will eventually be captured by the JVM, and the result of the JVM's processing is to print out the exception information and then terminate the program's operation.

4. The architecture of exception handling

All of the exception classes are derived from the exception class. This means that if we are not sure what type of exception will occur, we can declare a exception object directly in the catch, and we can catch all the exception classes and their subclasses ' exceptions. But pay attention to the order in which the catch is written. If there is more than one catch after a try and the exception object is declared in the first catch, the exception is processed directly by the first catch, which cannot be caught by subsequent catch. This error is generated when compiling the error. The following example:

public class Catchdemo 
{ 
  //Division operations Public 
  Static INT division (int A,int b) 
  { 
    return 
  /A/A;} public static void Main (string[] args) 
  { 
    try 
    { 
      catchdemo.division (4,0); 
    } 
    catch (Exception e) 
    { 
      System.out.println ("Exception Class"); 
    } 
    catch (ArithmeticException e) 
    { 
      System.out.println ("ArithmeticException Class"); 
    } 
  } 

The compiler output ArithmeticException has been captured, meaning that the above exception has captured this exception without having to repeat the capture.

What if you turn these two catch turns?

public class Catchdemo 
{ 
  //Division operations Public 
  Static INT division (int A,int b) 
  { 
    return 
  /A/A;} public static void Main (string[] args) 
  { 
    try 
    { 
      catchdemo.division (4,0); 
    } 
    catch (ArithmeticException e) 
    { 
      System.out.println ("ArithmeticException Class");
    } 
    catch (Exception e) 
    { 
      System.out.println ("Exception Class");
    } 
  } 

At this point, we found that the code was compiled, and that the result of the execution was that ArithmeticException caught the exception, and the subsequent catch was not captured.

I hope this article will help you with your Java programming.

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.