java当中异常的捕捉(try catch)

在程序运行过程中,难免会出现异常,这个时候Java中捕捉异常的语法格式进行异常的处理,java当中使用try catch语句进行异常的捕捉。
语法格式:

try {//尝试
	可能出现异常代码
} catch(异常对象) {//抓
 //针对于上面异常的处理方案
}
执行流程: 如果try里面的代码没有异常,跳过catch 然后接着往下执行。
 如果trye里面有异常,就执行catch后面大括号的代码

实例:

package com.qf.d_exception;

public class Demo1 {
	public static void main(String[] args) {
		test(3, 0);
	}
	public static void test(int a, int b) {
//		Exception in thread "main" java.lang.ArithmeticException: / by zero
//		at com.qf.d_exception.Demo1.test(Demo1.java:8)
//		at com.qf.d_exception.Demo1.main(Demo1.java:5)
		int c = 0;
		try {
			c = a / b;
			
		}catch (Exception e) {//catch  抓 捕捉
			//Exception e = new ArithmeticException(); 多态
			//jvm会抛出一个异常的实例(对象)  将对象赋值给ArithmeticException  e  = new ArithmeticException()
			System.out.println("代码有异常");
			System.out.println("除数不能为0");
		}
		System.out.println(c);
		
		System.out.println("嘻嘻");
	}
}```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值