标签:style blog color java io ar div log sp
从一个读取两个整数并显示商的例子:
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 ..."); } }
改用方法来计算商:
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 ..."); } }
标签:style blog color java io ar div log sp
原文地址:http://www.cnblogs.com/bigjava/p/3931704.html