Java Exception handling mechanism

Source: Internet
Author: User
Tags getmessage

Exception handling mechanism in Java:

The Java language provides two exception handling mechanisms: Catch exceptions and declare discard exceptions

1) Catch exception: When the Java program is running, the system gets an exception object, it will follow the method's call stack by layer, looking for the code to handle this exception. After finding a way to handle this type of exception, the runtime system gives the current exception to this method, and if no method can be found to catch the exception, the runtime system terminates and the corresponding Java program exits.

2) Declare discard exception: When the Java program runs the system gets an exception object, if a method does not know how to handle the exception, you can declare the discard exception when the method declares. Declaring an abandoned exception is indicated in the throws clause in a method declaration.

The exception handling mechanism in Java is illustrated by a few examples below

One: Aboutexception.java

Source:

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");     System.out.println (+k);}}}  

Results:

Analysis:

In the program, when the I,J data type is changed to Integer, the program throws exception error, which causes the program not to run properly, if the i,j is changed to double type, the output of the program is infinite;

Java Exception handling mechanism:

Put the code in the TRY statement block where the error may occur.
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.

Two: Catchwho.java

Source:

public class Catchwho {public     static void Main (string[] args) {         try {            try {                 throw new Arrayindexoutofboun Dsexception ();             }             catch (ArrayIndexOutOfBoundsException e) {                System.out.println (  "arrayindexoutofboundsexception" +  "/ Inner layer Try-catch ");             }             throw new ArithmeticException ();         }         catch (ArithmeticException e) {             System.out.println ("occurs ArithmeticException");         }         catch (ArrayIndexOutOfBoundsException e) {            System.out.println (  "arrayindexoutofboundsexception" + "/ Outer try-catch ");         }     } }

Operation Result:

Three: Catchwho2.java

Source:

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

Operation Result:

Four: Embedfinally.java

Source:

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.getc                Lass (). toString ());                } finally {System.out.println ("at level 3 finally");  }//result=100/0; Level 2} catch (Exception e) {System.out.println ("Level 2:" + E.getclass (). Tostri            Ng ());            } finally {System.out.println ("at level 2 finally");  }//result = 100/0; Level 1} catch (Exception e) {SYstem.out.println ("Level 1:" + e.getclass (). toString ()); } finally {.        System.out.println ("at level 1 finally"); }    }}

Run Result: The program cannot run!

Analysis: The source code in 69 lines out of a ".", if you delete it, there will be the following results:

V: Will the finally statement be executed?

Source:

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");        }    }}

Run:

Analysis:

When there are multiple layers of nested Finally, exceptions are thrown at different levels and thrown at different locations, which may cause different finally statement block execution order

VI: How to track the propagation path of an exception?

Source:

usingexceptions.java//demonstrating the GetMessage and printstacktrace//methods inherited into all exception classes. public class Printexceptionstack {public   static void Main (String args[])   {      try {         method1 ();      }      catch (Exception e) {         System.err.println (e.getmessage () + "\ n");         E.printstacktrace ();      }   }   public static void Method1 () throws Exception   {      method2 ();   }   public static void Method2 () throws Exception   {      method3 ();   }   public static void Method3 () throws Exception   {      throw new Exception (' Exception thrown in method3 ');}   }

Run:

Analysis:
When an exception occurs in the program, the JVM looks for the error handler in order of the method invocation.
You can use the Printstacktrace and GetMessage methods to understand what happens when an exception occurs:
Printstacktrace: Prints the method call stack.
Each object of the Throwable class has a GetMessage method that returns a string that is passed in the exception constructor and typically contains information about a particular exception.

Seven: Design program (according to the input = score, judge the level of the course of the door "including the exception handling mechanism, and no matter what the user input, will not crash")

Source:

Package Tichangchuli;import Java.util.Scanner; @SuppressWarnings ("Serial") class Chenjiexception extends exception{ Public Chenjiexception (String s) {super (s);}} public class Chengji {public static Boolean Test (String ss) {Boolean Flag=true;char []charr=ss.tochararray (); int l= Ss.length (); for (int i=0;i<l;i++) {if (charr[i]<48| | charr[i]>57) {flag=false;}} return flag;} public static void Main (string[] args) {//TODO auto-generated method Stub@suppresswarnings ("resource") Scanner in=new Sca Nner (system.in); System.out.println ("Please enter student results"); try{String U=in.next (), if (Test (U)) {int chengj=integer.parseint (u); if (chengj>=90 {System.out.println ("excellent");} else if (chengj<90&&chengj>=80) {System.out.println ("benign");} else if (chengj<80&&chengj>=70) {System.out.println ("Medium");} else if (chengj<70&&chengj>=60) {System.out.println ("Pass");} else {System.out.println ("failed");}} else throw new Chenjiexception ("The input format is incorrect!) ");} catch (Chenjiexception e) {System.out.println (e);}}}

Results:

Java Exception handling mechanism

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.