JAVA09 Exception Handling

Source: Internet
Author: User
Tags arithmetic getmessage

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

try{
Code that may have run errors;
}
catch (Exception type exception object reference) {
Code to handle the exception
}
finally{
Code for "Aftercare"
}

All the exceptions that can be caught in Java derive from the Exception class.

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 no appropriate exception handling code is provided, the JVM will end the entire application.

Three. Multi-layered anomaly capture-1

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
Throws two exceptions, handling the second time after the first processing is complete.

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) {//array subscript out of boundsSystem.out.println ("arrayindexoutofboundsexception" + "/outer try-catch"); }     } }

2) Results

3) Results Analysis

After an exception match finishes, the next exception cannot be executed, and the system cannot accumulate processing exceptions.

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 layers of nested Finally, exceptions are thrown at different levels and thrown at different locations, which can result in a different order of the finally statement block execution.


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

Not necessarily. Because when you run System.exit (0), the Java Virtual machine is terminated, resulting in the inability to execute the finally content.

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.

1) Source Code

//20161123 High Snow Tong/*Write a program that asks 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 classPrograss { Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in);        String Pro; System.out.println ("Please enter your score:");  while(true){        Try{Pro=Sc.nextline (); if(Pro.matches ("\\d*")){                Throw NewInexception ("Wrong input! No, it's not numbers! "); }            Else{                intproo=integer.parseint (PRO); System.out.print ("Input correct!" ");                Judge (Proo);  Break; }         }        Catch(inexception e) {System.out.print ("Please re-enter:");    }} sc.close (); }         Public Static voidJudgeintPro) {        if(pro>=0&&pro<60) System.out.println ("The result is not qualified!" "); Else if(pro<70) System.out.println ("The result is qualified!" "); Else if(pro<80) System.out.println ("In the grades!" "); Else if(pro<90) System.out.println ("Good grades!" "); Else if(pro<=100) System.out.println ("Excellent performance!" "); ElseSystem.out.println ("Input score does not match"); }}classInexceptionextendsexception{//     Publicinexception (String msg) {Super(msg); }}

2) Results

JAVA09 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.