当前位置:网站首页>异常处理机制二
异常处理机制二
2022-07-26 09:16:00 【肥常忧伤】
声明抛出异常
声明抛出异常是Java中处理异常的第二种方式
1、如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这 种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理, 而由该方法的调用者负责处理。
2、在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可 以是方法中产生的异常类型,也可以是它的父类。
声明抛出异常举例:


重写方法声明抛出异常的原则
重写方法不能抛出比被重写方法范围更大的异常类型。在多态的情况下, 对methodA()方法的调用-异常的捕获按父类声明的异常处理。
手动抛出异常
Java异常类对象除在程序执行过程中出现异常时由系统自动生成并 抛出,也可根据需要使用人工创建并抛出。
1、首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运 行环境)。 IOException e = new IOException();
throw e;
2、可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将 会产生语法错误:
throw new String(“want to throw”)
用户自定义异常类
1、 一般地,用户自定义异常类都是RuntimeException的子类
2、 自定义异常类通常需要编写几个重载的构造器。
3、 自定义异常需要提供serialVersionUID
4、 自定义的异常通过throw抛出。
5、 自定义异常最重要的是异常类的名字,当异常出现时,可以根据 名字判断异常类型。
用户自定义异常类MyException,用于描述数据取值范围错误信息。用户 自己的异常类必须继承现有的异常类。
总结:异常处理5个关键字
边栏推荐
- Rocky基础练习题-shell脚本2
- Datawhale panda book has been published!
- Advanced mathematics | Takeshi's "classic series" daily question train of thought and summary of error prone points
- Pat grade a a1076 forwards on Weibo
- 围棋智能机器人阿法狗,阿尔法狗机器人围棋
- Summary of common activation functions for deep learning
- NTT (fast number theory transformation) polynomial inverse 1500 word analysis
- 【Mysql】认识Mysql重要架构(一)
- 756. 蛇形矩阵
- Voice chat app source code - Nath live broadcast system source code
猜你喜欢

The essence of attack and defense strategy behind the noun of network security

Redis principle and usage - installation and distributed configuration

Advanced mathematics | Takeshi's "classic series" daily question train of thought and summary of error prone points

Uploading pictures on Alibaba cloud OSS

布隆过滤器

Study notes of automatic control principle -- correction and synthesis of automatic control system

2022年上海市安全员C证考试试题及模拟考试

Horizontal comparison of the data of the top ten blue chip NFTs in the past half year

优秀的 Verilog/FPGA开源项目介绍(三十零)- 暴力破解MD5

分布式跟踪系统选型与实践
随机推荐
ext3文件系统的一个目录下,无法创建子文件夹,但可以创建文件
QT | about how to use EventFilter
十大蓝筹NFT近半年数据横向对比
Numpy Foundation
Redis principle and usage - installation and distributed configuration
2022流动式起重机司机考试题模拟考试题库模拟考试平台操作
NTT (fast number theory transformation) polynomial inverse 1500 word analysis
CF1481C Fence Painting
Mutual transformation of array structure and tree structure
Canal 的学习笔记
Pat grade a A1034 head of a gang
Center an element horizontally and vertically
[leetcode database 1050] actors and directors who have cooperated at least three times (simple question)
Object 的Wait Notify NotifyAll 源码解析
Nuxt - 项目打包部署及上线到服务器流程(SSR 服务端渲染)
网络安全漫山遍野的高大上名词之后的攻防策略本质
Study notes of canal
分布式跟踪系统选型与实践
MySQL strengthen knowledge points
李沐d2l(六)---模型选择