Java Study Notes 12 -- Exception Handling and Study Notes 12 --

Source: Internet
Author: User

Java Study Notes 12 -- Exception Handling and Study Notes 12 --

Java learning notes series:

Java study note 11-Summary

Java Study Notes 10-generic Summary

Java study notes 9-internal class Summary

Java study note 8-interface Summary

Java study notes 7 -- abstract classes and abstract methods

Java study Note 6-class inheritance, Object class

Java study notes 5-Class Method

Java study note 4-object initialization and collection

Java Study Notes 3-Basics of classes and objects

Java study Note 2 -- data type, array

Java study Note 1-Summary of the development environment Platform

URL: http://www.cnblogs.com/archimedes/p/java-study-note12.html.

1. Exception Handling Overview

An example of reading two integers and displaying the operator:

public static void main(String args[]){    Scanner input = new Scanner(System.in);      System.out.print("Enter two integers: ");    int number1 = input.nextInt();    int number2 = input.nextInt();     System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); }

Enter two integers: 3 0

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

A simple solution is to add an if statement to test the second number:

public class Main{    public static void main(String args[])    {        Scanner input = new Scanner(System.in);                System.out.print("Enter two integers: ");        int number1 = input.nextInt();        int number2 = input.nextInt();        if(number2 != 0)            System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));        else            System.out.println("Divisor cannot be zero ");    }}

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

public class Main{    public static void main(String args[])    {        Scanner input = new Scanner(System.in);                System.out.print("Enter two integers: ");        int number1 = input.nextInt();        int number2 = input.nextInt();        try {            if(number2 == 0)                throw new ArithmeticException("Divisor cannot be zero");            System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));        }        catch(ArithmeticException ex) {            System.out.println("Exception: an integer " + "cannot be divided by zero ");        }        System.out.println("Execution continues ...");    }}
2. Benefits of Exception Handling

Use the following method to calculate the problem:

public class Main{    public static int quotient(int number1, int number2) {        if(number2 == 0)            throw new ArithmeticException("Divisor cannot be zero");        return number1 / number2;    }        public static void main(String args[])    {        Scanner input = new Scanner(System.in);                System.out.print("Enter two integers: ");        int number1 = input.nextInt();        int number2 = input.nextInt();        try {            int result = quotient(number1, number2);            System.out.println(number1 + " / " + number2 + " is " + result);        }        catch(ArithmeticException ex) {            System.out.println("Exception: an integer " + "cannot be divided by zero ");        }        System.out.println("Execution continues ...");    }}

The advantage of exception handling is to separate detection errors from handling errors.

3. Exception type

4. More about Exception Handling

Java Exception Handling model is based on three operations:Declare an exception, throw an exception, and capture an exception

Declared exception

If an exception is declared in a method, the keyword throws is used in the method header, as shown below:

public void myMethod throws Exception1,Exception2,……,ExceptionN

Throw an exception

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

Instance:

IllegalArgumentException ex = new IllegalArgumentException("Worng Argument");throw ex;

Or directly:

throw new IllegalArgumentException("Worng Argument");

Capture exceptions

When an exception is thrown, you can capture and process it in try-catch:

try {    statements;} catch (exception1 ex1){    handler for exception1;} catch (exception1 ex2){    handler for exception2;} ……catch (exception1 exN){    handler for exceptionN;}    

Obtain information from exceptions

You can use the methods in the Throwable class to obtain the exception information.

public class test {    public static void main(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(int i = 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 int sum(int[] list) {        int sum = 0;        for(int i = 0; i <= list.length; i++) {            sum += list[i];        }        return sum;    }}

Finally statement

Whether or not an exception occurs, you want to execute some code. You can use the finally clause:

public class test {    public static void main(String[] args) {        PrintWriter output = null;        try {            output = new PrintWriter("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");    }}

 

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.