diff --git a/javaSE-day05/src/com/inmind/custom_exception06/Demo11.java b/javaSE-day05/src/com/inmind/custom_exception06/Demo11.java new file mode 100644 index 0000000..85ad3d7 --- /dev/null +++ b/javaSE-day05/src/com/inmind/custom_exception06/Demo11.java @@ -0,0 +1,40 @@ +package com.inmind.custom_exception06; +/* +要求:我们模拟注册操作,如果用户名已存在,则抛出异常并提示:亲,该用户名已经被注册。 +使用异常来实现,用户名已注册的信息提示业务逻辑 + */ +public class Demo11 { + //定义一些已经存在的用户名(假数据,以后使用配置文件或者数据库) + static String [] usernames = {"tom","jack","rose"}; + + public static void main(String[] args) { + //定义一个变量接收用户输入的用户名 + String user = "jack"; + + //调用一个方法来判断当前用户名是否存在 + try { + regist(user); + //如果没有出现异常,就继续相应的操作即可 + //.... + } catch (RegistException e) { + e.getMessage();//获取一些自定义异常,与业务相关的信息 + System.out.println("捕获了注册异常后的处理"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println(e.getMessage()); + } + + System.out.println("程序结束"); + } + + private static void regist(String user) throws RegistException { + //遍历已有的用户名,逐一判断是否存在,存在就抛出一个异常 + for (String username : usernames) { + if (username.equals(user)) { + throw new RegistException("该用户名"+user+"已经存在"); + } + } + } + + +} diff --git a/javaSE-day05/src/com/inmind/custom_exception06/RegistException.java b/javaSE-day05/src/com/inmind/custom_exception06/RegistException.java new file mode 100644 index 0000000..594f0d7 --- /dev/null +++ b/javaSE-day05/src/com/inmind/custom_exception06/RegistException.java @@ -0,0 +1,14 @@ +package com.inmind.custom_exception06; +/* + 自定义异常: + 1.编译时异常:提醒代码有语法问题或者声明了某些异常(继承Exception) + 2.运行时异常:用来处理业务逻辑(继承RuntimeException) + */ +//public class RegistException extends Exception{//编译时异常 +public class RegistException extends RuntimeException{//运行时异常 + + public RegistException(String message) { + super(message); + } + //业务功能 +}