Java Learning note 12--exception handling

Source: Internet
Author: User
Tags throw exception

Java Learning Notes Series:

Java Learning Note 11--Collection summary

Java Learning Note 10--Generic summary

Java Learning Note 9--Internal class summary

Java Learning Note 8--Interface summary

Java Learning notes 7--abstract classes and abstract methods

Java Learning note 6--class inheritance, object class

Java Learning note Methods for 5--classes

Java Learning Note Initialization and recycling of 4--objects

Java Learning Notes Basics of 3--classes and objects

Java Learning notes 2--data types, arrays

Summary of Java Learning Note development environment platform

This article address: http://www.cnblogs.com/archimedes/p/java-study-note12.html, reprint please indicate source address.

1. Exception Handling Overview

Read two integers from one and show examples of the quotient:

 Public Static void Main (String args[]) {    new  Scanner (system.in);      System.out.print ("Enter integers:");     int number1 = input.nextint ();     int number2 = input.nextint ();      + "/" + Number2 + "is" + (Number1/ number2));}

Enter 0 Integers:3

Exception in thread "main" java.lang.ArithmeticException:/By zero
At Main.main (main.java:18)

An easy way to solve this is to add an if statement to test the second number:

 Public classmain{ Public Static voidMain (String args[]) {Scanner input=NewScanner (system.in); System.out.print ("Enter the integers:"); intNumber1 =Input.nextint (); intNumber2 =Input.nextint ();  if(number2! = 0 ) System.out.println (Number1+ "/" + Number2 + "is" + (Number1/number2)); ElseSystem.out.println ("Divisor cannot be zero"); }}

To demonstrate the concept of exception handling, including how to create, throw, catch, and handle exceptions, continue rewriting the above program as follows:

 Public classmain{ Public Static voidMain (String args[]) {Scanner input=NewScanner (system.in); System.out.print ("Enter the integers:"); intNumber1 =Input.nextint (); intNumber2 =Input.nextint (); Try {            if(Number2 = = 0)                Throw NewArithmeticException ("Divisor cannot be zero"); System.out.println (Number1+ "/" + Number2 + "is" + (Number1/number2)); }        Catch(ArithmeticException ex) {System.out.println ("Exception:an integer" + "Cannot is divided by zero"); } System.out.println ("Execution continues ..."); }}
2. Advantages of exception handling

Use the method to calculate the quotient:

 Public classmain{ Public Static intQuotient (intNumber1,intnumber2) {        if(Number2 = = 0)            Throw NewArithmeticException ("Divisor cannot be zero"); returnNumber1/number2; }         Public Static voidMain (String args[]) {Scanner input=NewScanner (system.in); System.out.print ("Enter the integers:"); intNumber1 =Input.nextint (); intNumber2 =Input.nextint (); Try {            intresult =Quotient (Number1, number2); System.out.println (Number1+ "/" + Number2 + "is" +result); }        Catch(ArithmeticException ex) {System.out.println ("Exception:an integer" + "Cannot is divided by zero"); } System.out.println ("Execution continues ..."); }}

The advantage of exception handling is that the detection error is separated from the processing error.

3. Exception type

4. More knowledge about exception handling

Java's exception handling model is based on three operations: declaring an exception, throwing an exception, catching an exception

declaring exceptions

Declaring an exception in a method is to use the keyword throws in the method header, as follows:

 Public void throws Exception1,exception2,......, Exceptionn

Throw exception

A program that detects an error can create an instance of the correct exception type and throw it

Instance:

New IllegalArgumentException ("worng Argument"); throw ex;

or directly:

Throw New IllegalArgumentException ("worng Argument");

Catching exceptions

When an exception is thrown, it can be captured and processed in Try-catch:

Try {    catch  (Exception1 ex1) {    forcatch  ( Exception1 ex2) {    for  exception2;} ... Catch (Exception1 exn) {    for  exceptionn;}    

Getting information from an exception

You can use the methods in the Throwable class to get information about the exception

 Public classTest { Public Static voidMain (string[] args) {Try{System.out.println (sum (New int[]{1,2,3,4,5})); } Catch(Exception ex) {ex.printstacktrace ();            System.out.println (Ex.getmessage ());            System.out.println (Ex.tostring ()); System.out.println ("Trace Info obtained from Getbacktrace"); Stacktraceelement[] Traceelements=Ex.getstacktrace ();  for(inti = 0; i < traceelements.length; i++) {System.out.print ("Monthod" +traceelements[i].getmethodname ()); System.out.println ("(" +traceelements[i].getclassname ()); System.out.println (Traceelements[i].getlinenumber ()+ ")"); }        }    }        Private Static intSumint[] list) {        intsum = 0;  for(inti = 0; I <= list.length; i++) {sum+=List[i]; }        returnsum; }}

Finally statement

Regardless of whether the exception appears and you want to execute some code, you can take the finally clause:

 Public classTest { Public Static voidMain (string[] args) {printwriter output=NULL; Try{Output=NewPrintWriter ("Wu.txt"); Output.println ("Wlecome tio Java"); } Catch(IOException ex) {ex.printstacktrace (); } finally {            if(Output! =NULL) Output.close (); } System.out.println ("End of the program"); }}

Java Learning note 12--exception handling

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.