当前位置:网站首页>自定义异常类及练习
自定义异常类及练习
2022-06-28 09:21:00 【用户9857551】
自定义异常类
Java提供的异常类不够用,需要自己定义。 格式:
public class XXXException extends Exception / RuntimeException{
添加一个空参的构造方法;
添加一个带异常信息的构造方法;
}
注意:1.自定义异常类一般以Exception结尾,说明该类是一个异常类。 2.自定义异常类,必须继承Exception或者RuntimeException 继承Exception:那么自定义的异常类是一个编译期异常,如果方法内部抛出了编译期异常,就必须处理这个异常throws或者try/catch 继承RuntimeException:运行期异常,可以不管,交给虚拟机。
练习:
模拟用户注册异常,如果用户名已经存在,则抛出异常,并提示。 分析: 1.使用数组保存注册过的用户名(数据库) 2.使用scanner获取用户输入的用户名(前端页面) 3.定义一个方法,对用户输入的用户名进行判断 遍历储存的用户名,获取每一个用户名进行比较 ture: 用户名存在:抛出regiserException异常,并说“亲你好,该用户名已经被注册了”。 false:继续遍历比较 如果循环结束了,还没有:恭喜你,注册成功。 接下来定义主方法:
定义方法判断方法:
在主方法里调用方法:
在写的时候记得抛异常。 如果用try/catch记得加一个return,结束方法,不然下边的代码还是执行。
边栏推荐
- A classic JVM class loaded interview question class singleton{static singleton instance = new singleton(); private singleton() {}
- 分而治之之经典Hanoi
- Fastjason filter field
- JDBC connection database (MySQL) steps
- JVM系列(2)——垃圾回收
- Use of Jasper soft studio report tool and solution of thorny problems
- 如何实现基于 RADIUS 协议的双因子认证 MFA?
- 详解final、finally和finalize
- P2394 yyy loves Chemistry I
- The digital human industry is about to break out. What is the market pattern?
猜你喜欢
Static page of pinyougou mall
数字人行业爆发在即,市场格局几何?
Test cases for learning the basic content of software testing (II)
SQL injection file read / write
Ingersoll Rand面板维修IR英格索兰微电脑控制器维修XE-145M
SQL optimization experience: from 30248 seconds to 0.001 seconds
1182:合影效果
Dbeaver connects to kingbasees V8 (ultra detailed graphic tutorial)
自动转换之-面试题
The digital human industry is about to break out. What is the market pattern?
随机推荐
Explain observer mode
Screen settings in the source code of OBS Live Room
Postman interface test
Using transform:scale causes the page mouse hover event to disappear
This article explains in detail the difficult problems and solutions faced by 3D cameras
Interpretation of new products: realm launched GT neo2 Dragon Ball customized version
Is it safe for Huatai Securities to open an account online? What is the handling process
1182:合影效果
PMP needs to master its own learning methods
How to reduce the risk of project communication?
在本类私有属性直接使用?new()在使用!!!
为什么SELECT * 会导致查询效率低?
硬盘基本知识(磁头、磁道、扇区、柱面)
Ingersoll Rand面板维修IR英格索兰微电脑控制器维修XE-145M
Quickly understand JVM structure and working principle
Campus honey decoration of APP course design (e-commerce platform)
分而治之之经典Hanoi
Applet: traverse the value of an array in the list, which is equivalent to for= "list" list An item in comment
Redis5.0 slot migration, free play (single machine migration cluster)
How to solve the problem of high concurrency and seckill