java异常处理
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 ..."); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。