Java-7-异常 01 - 03


Java异常 01 - 03

Java异常01 - Error和Exception

image-20221110155118391

image-20221110155144022

image-20221110155225513

Java异常02 - 捕获和抛出异常

  • 抛出异常
  • 捕获异常
  • 关键字
    • try
    • catch
    • finally
    • throw
    • throws

ctrl + alt + t

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test {

public static void main(String[] args) {
int a = 1;
int b = 0;

try{ //监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ // catch(想要捕获的异常类型)捕获异常,可以写多个catch,大的异常写下面
System.out.println("程序出现异常,变量b不能为0");
}finally {
System.out.println("finally");
}
}
}
  • 主动抛出异常 throw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Test {

public static void main(String[] args) {

}

//假设这个方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b){
if(b==0){
throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
}
}

}

throws和try catch是处理异常时用的两种方式,try catch就是直接捕获了异常,然后解决掉,throws就是把异常返回给了外面(多是调用这个函数的地方),在外面catch try。如果不采取以上两种措施中的一个,就有可能报错。

Java异常03 - 自定义异常及经验小结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package Demo01;

public class MyException extends Exception{
private int detail;

public MyException(int a){
this.detail = a;
}

@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package Demo01;

public class Test {

static void test(int a) throws MyException {
System.out.println("传递参数为:"+a);

if (a>10){
throw new MyException(a); //抛出
}

System.out.println("OK");
}

public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException=>"+e);
throw new RuntimeException(e);
}
}

}

Author: Liang Junyi
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Liang Junyi !
  TOC