1. 程式人生 > >異常處理方法 try catch finally

異常處理方法 try catch finally

try 程序 png info all 捕捉 12px ima finally

try catch finally的用法

package com.異常;

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

/**
 *     異常
 * @author Administrator
 *    try catch finally用法
 */
public class Test1 {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        System.out.println(
"請輸入1~3之間任一個數字,程序將輸出相應的課程名字"); try {                          //嘗試 int key=sc.nextInt(); switch (key) { case 1: System.out.println("java課程"); break; case 2: System.out.println("大數據課程");
break; case 3: System.out.println("c語言課程"); break; default: System.out.println("沒有該課程!"); break; }  } catch (InputMismatchException e) {      //捕捉異常 System.err.println("輸入的不是數字"); e.printStackTrace();             //打印異常堆棧信息 }
catch (Exception e) { System.err.println("輸入錯誤"); }finally {                      //執行最終代碼 System.out.println("歡迎提出建議!"); } } }

測試

正常情況

技術分享圖片

輸入不是數字情況

技術分享圖片

異常處理方法 try catch finally