异常处理机制
- 抛出异常
- 捕获异常
- 异常处理五关键字: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);
}
}

捕获异常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");
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
运行结果:
程序出现异常,变量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();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
运行结果:
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();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
