1. 程式人生 > >捕獲異常try-catch-finally

捕獲異常try-catch-finally

但是 arc sys urn test === except 所有 true

異常分類

技術分享圖片

try-carch-finally出現規則

技術分享圖片

return關鍵字的使用

finally中慎用return,雖然語法上沒錯,但是由於finally的強制執行,影響邏輯上需要return的值

package com.mpp.test;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TryDemoOne {
    public static void main(String[] args) {
     /*   //要求:定義兩個整數,輸出兩數之商

        int one = 12;
        int two =2;
        System.out.println("one和two的商是:"+one/two);
     
*/ //要求:定義兩個證書,接受用戶的鍵盤輸入,輸出兩數之商 Scanner input = new Scanner(System.in); System.out.println("=========運算開始======="); try { System.out.print("請輸入第一個整數:"); int one = input.nextInt(); System.out.print("請輸入第二個整數:"); int two = input.nextInt(); System.out.println(
"one和two的商是:" + one / two); } //多重catch結構 catch (ArithmeticException e){ //算數異常 System.exit(1); //終止程序運行 e.printStackTrace(); //打印錯誤信息,出現位置隨機,無固定位置 System.out.println("除數不允許為零"); } catch (InputMismatchException e){ System.out.println(
"請輸入整數"); e.printStackTrace(); } catch (Exception e){//當還有不可知異常被拋出時,放一個Exception捕獲所有異常 System.out.println("出錯"); } finally {//無論怎樣都會執行的代碼 System.out.println("=========運算結束======="); } } }

return慎用實例:

package com.mpp.test;

import java.util.Scanner;

public class TryDemoTwo {
    public static void main(String[] args) {
        int res = test();
        System.out.println("one和two的商是:" + res);
    }

    public static int test(){
        Scanner input = new Scanner(System.in);
        System.out.println("=========運算開始=======");
        try {
            System.out.print("請輸入第一個整數:");
            int one = input.nextInt();
            System.out.print("請輸入第二個整數:");
            int two = input.nextInt();
            return one/two;
        }
        catch (ArithmeticException e){ //算數異常
            System.out.println("除數不允許為零");
            return 0;
        }
        finally {//無論怎樣都會執行的代碼
            System.out.println("=========運算結束=======");
//            return -10000000;   finally中慎用return,雖然語法上沒錯,但是由於finally的強制執行,影響邏輯上需要return的值
        }
    }
}

  

捕獲異常try-catch-finally