s-day05--自定义异常案例
This commit is contained in:
@@ -0,0 +1,32 @@
|
|||||||
|
package com.inmind.exception01;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
//要求:我们模拟登陆操作,如果用户名已存在,则抛出异常并提示:亲,该用户名已经被注册
|
||||||
|
public class Demo11 {
|
||||||
|
static String[] usernames = {"jack","tom","rose"};
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
Scanner sc = new Scanner(System.in);
|
||||||
|
System.out.println("请输入用户名:");
|
||||||
|
String username = sc.nextLine();
|
||||||
|
regist(username);
|
||||||
|
System.out.println(username+"注册成功");
|
||||||
|
} catch (RegistException e) {
|
||||||
|
String msg = e.getMessage();
|
||||||
|
System.out.println(msg);
|
||||||
|
}
|
||||||
|
System.out.println("程序结束");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void regist(String username) {
|
||||||
|
//如果传入用户名,已经在数组中存在了,说明已经注册过了,那我们主动抛出一个业务异常RegistException,并携带业务信息
|
||||||
|
for (String u : usernames) {
|
||||||
|
if (u.equals(username)) {
|
||||||
|
throw new RegistException("该用户名"+username+"已存在,请重新输入");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//如果没有抛出异常,说明注册业务是正确。
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.inmind.exception01;
|
||||||
|
/*
|
||||||
|
自定义异常:
|
||||||
|
1.编译时异常:提醒代码有语法问题或者声明了某些异常(继承Exception)
|
||||||
|
2.运行时异常:用来处理业务逻辑(继承RuntimeException)
|
||||||
|
*/
|
||||||
|
public class RegistException extends RuntimeException{
|
||||||
|
public RegistException() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public RegistException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user