From 8d3c857be34f44197c0e92f1eed07d7d89f9312d Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 4 Feb 2026 15:03:00 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E9=98=B6day05-=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/inmind/custom_exception06/Demo11.java | 40 +++++++++++++++++++ .../custom_exception06/RegistException.java | 14 +++++++ 2 files changed, 54 insertions(+) create mode 100644 javaSE-day05/src/com/inmind/custom_exception06/Demo11.java create mode 100644 javaSE-day05/src/com/inmind/custom_exception06/RegistException.java 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); + } + //业务功能 +}