Java异常

Java异常

  1. throws & throw
    如果方法声明后有throw语句,则在此方法被调用时,需要在调用方法中用try和catch进行异常捕获,如果不捕获异常,则需要在调用方法中使用throws语句将异常抛出。
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
import java.util.*;
public class Main {


public static void A(int a)throws Exception,IllegalArgumentException{
if(a == 0) {
throw new Exception("a=0,silly boy!");
}else if(a == 1) {
IllegalArgumentException str=new IllegalArgumentException("a=1, IllegalArgumentException");
throw str;
}
}

public static void main(String[] args) {
int a;
Scanner t = new Scanner(System.in);
try {
a = t.nextInt();
A(a);
}catch(IllegalArgumentException e2) {
System.out.println(e2.toString());
}catch(Exception e){
System.out.println(e.toString());
}

}
}

例如我们在上面的代码里定义了一个A方法,在这个方法里我们用throws声明了可能抛出的异常,然后我们需要在方法体里把异常实例化并且利用throw将其抛出。

在主方法中,我们利用try-catch语句,将可能出现异常的语句用try包括起来,然后利用catch语句来承接这个异常,并且输出异常。

那么接下来就是另外一个问题

  1. toString, getMessage, printStackTrace
    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
    31
    import java.util.*;
    public class Main {


    public static void A(int a)throws Exception,IllegalArgumentException{
    if(a == 0) {
    throw new Exception("a=0,silly boy!");
    }else if(a == 1) {
    IllegalArgumentException str=new IllegalArgumentException("a=1, bitch");
    throw str;
    }
    }

    public static void main(String[] args) {
    int a;
    Scanner t = new Scanner(System.in);
    try {
    a = t.nextInt();
    A(a);
    }catch(IllegalArgumentException e2) {
    System.out.println(e2.toString());
    System.out.println();
    System.out.println(e2.getMessage());
    System.out.println();
    e2.printStackTrace();
    }catch(Exception e){
    System.out.println(e.toString());
    }

    }
    }

输入1,结果:

1
2
3
4
5
6
7
8
9
10

java.lang.IllegalArgumentException: a=1, bitch

a=1, bitch

java.lang.IllegalArgumentException: a=1, bitch
at 异常.Main.A(Main.java:10)
at 异常.Main.main(Main.java:20)

`

  1. 最后还有一点,子类父类的问题
    子类异常要放在前面,父类异常要写在后面

-------------本文结束感谢您的阅读-------------