用户注册----自添加异常显示
public class UerService { public static void register (String username, String password) throws IllegalNameException { if(username == null || username.length() < 4 ||username.length() >11 ){ //System.out.println("用户名不合法,长度必需在[4~11]之间"); //return; throw new IllegalNameException("用户名不合法,长度必须在[4~11]之间"); } //执行到此处,说明没有产生异常 System.out.println("注册成功,欢迎["+username+"]"); } } //创建一个自定义异常类IllegalNameException public class IllegalNameException extends Exception{ public IllegalNameException(){ } public IllegalNameException(String s){ super(s); } } public class Test { public static void main(String[] args) { UerService uerService = new UerService(); try { uerService.register("hhh","321"); } catch (IllegalNameException e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }