Java基础编程题目——自定义异常类型,用户名长度小于3时抛出异常

使用继承 Exception 类的方式来自定义异常,只需要继承 Exception,再将信息传递给父类就可以了:

import java.util.Scanner;

public class Task {
    public static void main(String[] args) throws MyException {
        Scanner sc = new Scanner(System.in);
        String username = sc.next();
        if (username.length() < 3) {
            throw new MyException("用户名小于三位");
        }
        else
            System.out.println("用户名格式正确");
    }
}

class MyException extends Exception {
    private static final long serialVerdionUID = 1L;
    public MyException() {
    }
    public MyException(String msg) {
        super(msg);
    }
}

你可能感兴趣的:(Java编程题目)