Java Exception Handling

Source: Internet
Author: User

I. Hands-on Brain run Aboutexception.java example to learn the basics of implementing exception handling in Java.

1) Source Code

Importjavax.swing.*;classaboutexception { Public Static voidMain (string[] a) {DoubleI=-1, j=0, K; K=i/J; Try{k= i/j;//causes Division-by-zero Exception//throw new Exception ("hello.exception!");    }        Catch(ArithmeticException e) {System.out.println ("was removed by 0. "+e.getmessage ()); }        Catch(Exception e) {if(Einstanceofarithmeticexception) System.out.println ("Divide by 0"); Else{System.out.println (E.getmessage ()); }    }    finally{Joptionpane.showconfirmdialog (NULL, "OK" +k); //Joptionpane.showinternalconfirmdialog (null, k);     }  }}

2) Results

3) Results Analysis

When the first k=i/j is deleted, the result is normal operation and the anomaly detection code is used:

try{   // code where a run error may occur;  }  catch(Exception type   exception object reference) {    // code to handle the exception   }  finally{   // code for "aftercare" (free)  }

Two. Using the Java exception handling mechanism

? Put the code that could have errors in the TRY statement block.
? An exception object is thrown when the program detects that an error has occurred. The exception handling code captures and handles this error. The code in the Catch statement block is used to handle errors.
? When an exception occurs, the program control process jumps from the TRY statement block to the catch statement block.
? The statements in the finally statement block are always guaranteed to be executed, regardless of whether an exception occurs.
? If you do not provide the appropriate exception handling code, the JVM will end the entire application.

Three. Multi-layered abnormal capture of the brain

1) Source Code

 Public classcatchwho { Public Static voidMain (string[] args) {Try {                 Try {                     Throw NewArrayIndexOutOfBoundsException ();//array subscript out of bounds                }                 Catch(arrayindexoutofboundsexception e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/Inner layer Try-catch"); }            Throw NewArithmeticException ();//Arithmetic Exceptions        }         Catch(ArithmeticException e) {//Arithmetic ExceptionSystem.out.println ("Occurred arithmeticexception"); }         Catch(ArrayIndexOutOfBoundsException e) {//array subscript out of boundsSystem.out.println ("arrayindexoutofboundsexception" + "/outer try-catch"); }     } }

2) Results

3) Results Analysis
Nested mode of Try: Handles an internal try, throws an exception, and accepts processing. The second exception handler is thrown the second time after the first processing is completed.

Four. Multi-layered anomaly capture (2)

1) Source Code

 Public classCatchWho2 { Public Static voidMain (string[] args) {Try {                Try {                     Throw Newarrayindexoutofboundsexception (); }                 Catch(ArithmeticException e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/Inner layer Try-catch"); }            Throw NewArithmeticException (); }         Catch(ArithmeticException e) {System.out.println ("Happened ArithmeticException"); }         Catch(arrayindexoutofboundsexception e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/outer try-catch"); }             } }//throw and receive one should a answer

2) Results

Five. Hands-on brain when there are multiple nested try...catch...finally, pay special attention to the time when the finally is executed.

1) Source Code

 Public classembededfinally { Public Static voidMain (String args[]) {intresult; Try{System.out.println ("In Level 1"); Try{System.out.println ("In Level 2"); //result=100/0; //Level 2                 Try{System.out.println ("In Level 3"); Result=100/0;//Level 3                }                                 Catch(Exception e) {System.out.println ("Level 3:" +E.getclass (). toString ()); }                                finally{System.out.println ("In Level 3 finally"); }                              //result=100/0; //Level 2                }                      Catch(Exception e) {System.out.println ("Level 2:" +E.getclass (). toString ()); }             finally{System.out.println ("In Level 2 finally"); }                         //result = 100/0; //Level 1        }                 Catch(Exception e) {System.out.println ("Level 1:" +E.getclass (). toString ()); }                finally{System.out.println ("In Level 1 finally"); }        }}

2) Results

3) Results Analysis

When there are multiple nested try...catch...finally, exceptions are accepted at different locations, which can result in the order of the Finally statement block execution below the exception.

Six. Does the hands-on brain finally statement block certainly execute?

1) source program

 Public classsystemexitandfinally { Public Static voidMain (string[] args) {Try{System.out.println ("In Main"); Throw NewException ("Exception is thrown in main"); //system.exit (0);        }        Catch(Exception e) {System.out.println (E.getmessage ()); System.exit (0); }        finally{System.out.println ("In finally"); }        }}

2) Results

3) Results Analysis

When the diagram is System.exit (0); When executed, the program is closed and the following finally is no longer performed.

Seven. Hands-on brain

Write a program that requires the user to enter an integer at run time, representing the exam results of a course, followed by a "fail", "Pass", "Medium", "good", "excellent" conclusion.
Requires that the program be robust enough that it does not crash regardless of what the user enters.

ImportJava.util.*; Public classScore {StaticScanner in=NewScanner (system.in);  Public Static voidMain (string[] args) {System.out.println ("Input score:");        Judge (); }         Public Static voidjudge () {intN=-1;  while(n<0| | n>100){                    Try{n=In.nextint (); }            Catch(inputmismatchexception e) {System.out.println ("Bad format!" Re-enter! ");            In.nextline (); }        if(n>=0&&n<60) System.out.println ("Not qualified!" "); Else if(n>=60&&n<70) System.out.println (Qualified "); Else if(n>=70&&n<80) System.out.println (In "); Else if(n>=80&&n<90) System.out.println (Good "); Else if(n>=90&&n<=100) System.out.println (Excellent "); Else if(n>100) System.out.println ("Input score does not match"); }    }}

2) Results

Java Exception Handling

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.