在程序运行过程中,难免会出现异常,这个时候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("嘻嘻");
}
}```