Java09 hands the Brain

Source: Internet
Author: User
Tags getmessage

I. Hands-on Brain run Aboutexception.java example

1) Source Code

Import Javax.swing.*;class aboutexception {public   static void Main (string[] a)    {      double i=-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 ("removed by 0.  ") + e.getmessage ());    }        catch (Exception e)    {        if (e instanceof arithmeticexception)            System.out.println ("divide by 0");        else        {              System.out.println (e.getmessage ());            }    }    Finally     {             joptionpane.showconfirmdialog (null, "OK  " +k);             Joptionpane.showinternalconfirmdialog (null, k);     }  }

}
 

Results analysis

try{//code where a run error may occur;}

catch (Exception type exception object reference) {//code to handle 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 you do not provide the appropriate exception handling code, the JVM will end the entire application.

Three. Multi-layered anomaly capture-1

1) Source Code

public class Catchwho {public     static void Main (string[] args) {         try {                 try {                     throw new Arrayindexoutofboun Dsexception (); Array subscript out of bounds                }                 catch (ArrayIndexOutOfBoundsException e) {                        System.out.println (  " ArrayIndexOutOfBoundsException "+  "/inner layer Try-catch ");                 }            throw new ArithmeticException (); Arithmetic exception        }         catch (ArithmeticException e) {//Arithmetic exception            System.out.println ("occurs ArithmeticException");         }         catch (ArrayIndexOutOfBoundsException e) {//array subscript out of bounds           System.out.println (  "ArrayIndexOutOfBoundsException" + "/outer try-catch");         }     } }

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 class CatchWho2 {public     static void Main (string[] args) {         try {                try {                     throw new Arrayindexoutofbou Ndsexception ();                 }                 catch (ArithmeticException e) {                     System.out.println ("arrayindexoutofboundsexception" + "/Inner layer Try-catch");                 }            throw new ArithmeticException ();         }         catch (ArithmeticException e) {             System.out.println ("occurs ArithmeticException");         }         catch (ArrayIndexOutOfBoundsException e) {//array subscript out of bounds            System.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 class Embededfinally {public static void main (String args[]) {int result;             try {System.out.println ("in Level 1");  try {System.out.println ("in Level 2");  result=100/0;                                          Level 2 try {System.out.println ("at Level 3");  result=100/0; Level 3} catch (Exception e) {System                                . OUT.PRINTLN ("Level 3:" + E.getclass (). toString ());                                } finally {System.out.println ("at level 3 finally");  }//result=100/0; Level 2} catch (Exception e) {System.ou          T.println ("Level 2:" + E.getclass (). toString ());              } finally {System.out.println ("at level 2 finally");  }//result = 100/0; Level 1} catch (Exception e) {System.out.println (' Level 1: ' + e.g                Etclass (). toString ());                } finally {System.out.println ("at level 1 finally"); }        }}

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 class Systemexitandfinally {public       static void Main (string[] args)    {                try{            System.out.println ( "in Main");            throw new Exception ("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");        }        }}

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

 
Import java.util.*;p Ublic class Prograss {public static void main (string[] args) {Scanner sc=new Scanner (syste        m.in);        String Pro;        System.out.println ("Please enter your score:");            while (true) {try{pro=sc.nextline (); if (Pro.matches ("\\d*")) {throw new inexception ("wrong input! No, it's not numbers!            ");                } else{int Proo=integer.parseint (PRO); System.out.print ("Input correct!                ");                Judge (Proo);            Break        }} catch (Inexception e) {System.out.print ("Please re-enter:");    }} sc.close (); } public static void judge (int pro) {if (pro>=0&&pro<60) System.out.println ("Grade unqualified!        "); else if (pro<70) System.out.println ("Score qualified!        "); else if (pro<80) System.out.println ("in the score!        "); else if (pro<90) System.out.println ("Good grades!        "); else if (pro<=100) System. OUT.PRINTLN ("Excellent performance!        ");    else System.out.println ("Input score does not match");    }}class Inexception extends exception{//public inexception (String msg) {super (MSG); }}


Java09 hands the Brain

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.