try...catch的使用

沒有try…catch,程序執行出現了異常,程序會停止執行之後的代碼;
如果有了try…catch,程序的出現的異常會被捕獲和處理,異常之後的代碼仍能繼續執行。

一、沒有try…catch

package com.exception.test;

import java.util.Scanner;

public class TryCatch {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a,b,c;
        a=sc.nextInt();
        b=sc.nextInt();
        c=a%b;
        System.out.println("餘數爲:"+c);

        System.out.println("程序繼續執行");
    }
}

結果:
堅持比努力更重要
二、有try…catch

try…catch 包圍快捷鍵 Ctrl+Alt+T

package com.exception.test;

import java.util.Scanner;

public class TryCatch {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a,b,c;
        try {
            a=sc.nextInt();
            b=sc.nextInt();
            c=a%b;
            System.out.println("餘數爲:"+c);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("程序繼續執行");
    }
}

結果:
堅持比努力更重要

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章