java——第十二章 异常处理和文本I/O

1.异常处理:

使用try_throw_catch块模块

优点:将检测错误(由被调用的方法完成)从处理错误(由调用方法完成)中分离出来。

例子:

 1 package test;
 2 import java.util.Scanner;
 3 public class Demo {
 4 
 5     public static void main(String[] args) {
 6         
 7     Scanner input = new Scanner(System.in);
 8     System.out.print("Enter two integers: ");
 9     int number1 = input.nextInt();
10     int number2 = input.nextInt();
11     
12     try {  //try块包含正常情况下执行的代码
13     int result = quotient(number1,number2);
14     System.out.println(number1 + " / "+ number2 + " is "+result);
15     }
16     catch(ArithmeticException ex)   //异常被catch所捕获
17     {
18         System.out.println("Exception: an integer " + " Cannot be divided by zero ");
19     }
20     System.out.println("Execution continues...");
21     }
22     
23     public static int quotient(int number1,int number2)
24     {
25         if(number2==0)
26         {
27             throw new ArithmeticException("Divisor cannot be zero");
28             //System.exit(1);//表示非正常退出程序
29         }
30         return number1/number2;
31     }
32 }

例子二:输入类型有错误,抛出异常

 1 package test;
 2 import java.util.*;//代表你导入了java.util包中的所有类,,
 3 public class Demo {
 4 
 5     public static void main(String[] args) {
 6         
 7     Scanner input = new Scanner(System.in);
 8     boolean continueInput = true;
 9     
10     do {
11         try {
12             System.out.print("Enter an integers: ");
13             int number = input.nextInt();
14             
15             System.out.println("The number entered is "+ number);
16             continueInput = false;
17         }
18         catch(InputMismatchException ex)
19         {
20             System.out.println("try again.(" + "Incorrect input: an integer id=s required)");
21             input.nextLine();//接受输入的一行数据 以/r为结束
22         }
23     }while(continueInput);
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/Aiahtwo/p/9956262.html