From 2e366f7d61ac6250374c32359d8ec7be22705b27 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 5 Aug 2026 13:59:25 +0800 Subject: [PATCH] =?UTF-8?q?s-day05-=E8=87=AA=E5=AE=9A=E4=B9=89=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E6=A1=88=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/inmind/custom_exception06/Demo12.java | 41 +++++++++++++++++++ .../custom_exception06/RegisterException.java | 18 ++++++++ 2 files changed, 59 insertions(+) create mode 100644 s-day05/src/com/inmind/custom_exception06/Demo12.java create mode 100644 s-day05/src/com/inmind/custom_exception06/RegisterException.java diff --git a/s-day05/src/com/inmind/custom_exception06/Demo12.java b/s-day05/src/com/inmind/custom_exception06/Demo12.java new file mode 100644 index 0000000..31bb260 --- /dev/null +++ b/s-day05/src/com/inmind/custom_exception06/Demo12.java @@ -0,0 +1,41 @@ +package com.inmind.custom_exception06; + +import java.util.Scanner; + +/* +在上述代码中,发现这些异常都是JDK内部定义好的,但是实际开发中也会出现很多异常,这些异常很可能在JDK中没有定义过, +例如年龄负数问题,考试成绩负数问题.那么能不能自己定义异常呢? + +要求:我们模拟注册操作,如果用户名已存在,则抛出异常并提示:亲,该用户名已经被注册。 +使用异常来实现,用户名已注册的信息提示业务逻辑 + */ +public class Demo12 { + //静态变量表示已经注册过的用户名 + 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(); + //判断下该用户名是否可用 + checkUsername(username); + System.out.println("恭喜你,注册成功!"); + } catch (RegisterException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + System.out.println("程序结束"); + } + //使用自定义的异常,来处理用户名已注册的业务场景 + private static void checkUsername(String username) { + for (String u : usernames) { + if (u.equals(username)) { + //主动抛出异常 + throw new RegisterException("亲,该用户名已经被注册"); + } + } + } + +} diff --git a/s-day05/src/com/inmind/custom_exception06/RegisterException.java b/s-day05/src/com/inmind/custom_exception06/RegisterException.java new file mode 100644 index 0000000..41a3045 --- /dev/null +++ b/s-day05/src/com/inmind/custom_exception06/RegisterException.java @@ -0,0 +1,18 @@ +package com.inmind.custom_exception06; +/* +自定义异常: + 1.编译时异常:提醒代码有语法问题或者声明了某些异常(继承Exception) + 2.运行时异常:用来处理业务逻辑(继承RuntimeException) + */ +public class RegisterException extends RuntimeException{ + //默认无参构造方法 + public RegisterException(){ + super();//不写,编译器也会自动加 + } + + //有参构造方法 + public RegisterException(String msg){ + super(msg);//调用父类的构造方法,将msg保存下来 + } + +}