1. 程式人生 > >java——第十二章 異常處理和文字I/O

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 }