欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA中对异常抛出时的疑问

程序员文章站 2022-03-17 20:51:41
...

怎么才能使输入字母时,把错误抛出来呢?怎么样才能在输入错误数字后,重新在输入呢?求解答,各位大佬们,来自一位初学者请求!嘿嘿嘿
JAVA中对异常抛出时的疑问
JAVA中对异常抛出时的疑问

异常类
package com.company;

public class OutException extends Exception {
public OutException(){
super();
}
public OutException(String message){
super(message);
}
}
方法类
package com.company;
import java.util.InputMismatchException;
import java.util.Scanner;
public class EmployeeTest {

public static void main(String[] args) {
        int employeeId;
        int department;
        String employeeName;
    Scanner sc = new Scanner(System.in);
    System.out.println("----欢迎进入测试异常员工查询系统----");
    System.out.println("您已进入程序,请进行测试!");
    System.out.println("请输入您要选择的部门");
    department = sc.nextInt();
    try {
        switch (department) {
            case 1:
                System.out.println("欢迎进入1部门");
                break;
            case 2:
                System.out.println("欢迎进入2部门");
                break;
            case 3:
                System.out.println("欢迎进入3部门");
                break;
            case 4:
                System.out.println("欢迎进入4部门");
                break;
            case 5:
                System.out.println("欢迎进入5部门");
                break;
            default:
                System.out.println();
                if (department > 6) {
                    System.out.println("对不起,并未查询到所选编号部门");
                    throw new OutException("您所选择的部门大于了数字5");
                }else if (department!=sc.nextInt()){
                    throw new InputMismatchException(){};
                }
        }
    } catch (InputMismatchException I) {
        System.out.println(("对不起您输入的数字类型错误"));
    } catch (OutException O) {
        System.out.println(O.getMessage());

    } finally {
        System.out.println("请输入您要选择的员工编号");
        employeeId = sc.nextInt();
        System.out.println("请输入您要查询的员工姓名");
        employeeName = sc.next();
        System.out.println("员工编号:" + employeeId +"  "+ "姓名:" + employeeName+"  " +
                "部门编号:" + department);
    }

}

}