进阶day05-自定义异常
This commit is contained in:
40
javaSE-day05/src/com/inmind/custom_exception06/Demo11.java
Normal file
40
javaSE-day05/src/com/inmind/custom_exception06/Demo11.java
Normal file
@@ -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+"已经存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
//业务功能
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user