码迷,mamicode.com
首页 > 编程语言 > 详细

java异常处理

时间:2014-08-25 19:10:44      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   java   io   ar   div   log   sp   

1、异常处理概述

从一个读取两个整数并显示商的例子:

    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)

解决的一个简单的办法是添加一个if语句来测试第二个数字:

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

为了演示异常处理的概念,包括如何创建、抛出、捕获以及处理异常,继续改写上面的程序如下:

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、异常处理的优势

改用方法来计算商:

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

 

java异常处理

标签:style   blog   color   java   io   ar   div   log   sp   

原文地址:http://www.cnblogs.com/bigjava/p/3931704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!