当前位置:网站首页>异常处理Exception
异常处理Exception
2022-07-25 09:27:00 【看小虫子】
1,抛出异常
①,方法中异常的抛出与捕获
//在主函数中
try{
new A().test(1,0);}
catch (ArithmeticException e){
e.printStackTrace();
}
//假设这个方法中,处理不了这个异常,方法就主动抛出异常
//方法中抛出异常然后在主函数中捕获异常就可以保证程序正常运行
public void test(int a ,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException(); //主动抛出异常 一般在方法中使用
}
②,程序执行时可能会碰到的异常,直接抛出
if(b==0){
throw new ArithmeticException(); //主动抛出异常 一般在方法中使用
}
2,捕获异常
>VirtulMachineError
顺序 Throwable>Error>AWTError
>Exception>IOExeception
>RUNtimeException
//Ctrl+Alt+T 可以快捷生成异常捕获机制
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();//打印捕获的栈信息
} finally {
}
//假设要捕获多个异常就顺序需要从小到大
try{
new demo01().a();
}catch (Error e){
System.out.println("被除数不能为零");
}catch ( Exception e){
System.out.println("Exception");
}
catch (Throwable e){
System.out.println("Throwable");
}
//finally可以不要
finally {
System.out.println("finally");
}
3,自定义异常
为了实现一些不是异常但有条件限制的操作
//定义一个变量接收值>10报异常
private int detail;
//构造器
public MyException(int a){
this.detail=a;
}
//toString :异常的打印信息
@Override
public String toString() {
return "MyException{"+detail +'}';
}
-------------------------
public class Test {
//可能会存在异常的方法
static void test(int a){
System.out.println("传递的参数为"+a);
if(a>10){
try {
throw new MyException(a);
} catch (MyException e) {
e.printStackTrace();
}
}
System.out.println("OK");
}
public static void main(String[] args) {
test(11);
}
4,异常总结
1,在多重异常可以在最后加一个catch(Exception)来处理可能遗漏的异常
2,尽量去处理异常,切忌简单的调用printStackTrace()去打印输出
3,尽量添加finally 语句块去释放一些占用的资源
边栏推荐
猜你喜欢

小程序调起微信支付

emmet语法速查 syntax基本语法部分

Common methods of nodejs version upgrade or switching

Subtotal of rospy odometry sinkhole
![[recommended collection] with these learning methods, I joined the world's top 500 - the](/img/95/e34473a1628521d4b07e56877fcff1.png)
[recommended collection] with these learning methods, I joined the world's top 500 - the "fantastic skills and extravagance" in the Internet age

VLAN的配置及其应用(以华为eNSP为例)

canal实现mysql数据同步

Use of dictionary tree

vscode插件开发

数论--负进制转换
随机推荐
Record of deep learning segment error (segment core/ exit code 139)
几个常用的网络诊断命令
数论---最大公约数最小公倍数
Round to the nearest
多线程——Runnable接口,龟兔赛跑
Summary of most consistency problems
oracle 解析同名xml 问题
GCD详解
[recommended collection] with these learning methods, I joined the world's top 500 - the "fantastic skills and extravagance" in the Internet age
修改mysql的分组报错Expression #1 of SELECT list is not in GROUP
The economic basis of a hardware siege lion
概率机器人学习笔记第二章
UE4 碰撞(Collsion)
用户喜好
史上最全面的UE4 文件操作,打开,读、写,增、删、改、查
第五阶段第一周
nodejs版本升级或切换的常用方式
cookie and session
Redis使用场景
JS uses requestanimationframe to detect the FPS frame rate of the current animation in real time