异常处理机制
- 抛出异常
- 捕获异常
- 异常处理五关键字:try, catch, finally, throw, throws
package com.jacyzhu.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
System.out.println(a/b);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/9552653782da4e0786ba79993b7be0e1.png)
捕获异常1
package com.jacyzhu.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a/b);
}catch (ArithmeticException e) {
System.out.println("程序出现异常,变量b不能为0");
}finally {
System.out.println("finally");
}
}
}
运行结果:
程序出现异常,变量b不能为0"
finally
捕获异常2
package com.jacyzhu.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().a();
}catch (Error e) {
System.out.println("Error");
}catch (Exception e) {
System.out.println("Exception");
}catch (Throwable t) {
System.out.println("Throwable");
}finally {
System.out.println("finally");
}
}
public void a() {
b();
}
public void b() {
a();
}
}
运行结果:
Error
finally
抛出异常,捕获异常3
package com.jacyzhu.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1, 0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a, int b) throws ArithmeticException{
if (b == 0) {
throw new ArithmeticException();
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/5b6247bf19be4144b61a40b572d8d3a6.png)