02.异常处理
# 01.异常处理
# 1.1 try catch
public class Test{
public static void main( String args[] ) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[8]);
} catch (Exception e) {
System.out.println(e); // java.lang.ArrayIndexOutOfBoundsException: 8
}
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 1.2 finally
finally
语句可以在try catch
之后执行代码,而不管是否在try代码中出现异常
public class Test{
public static void main( String args[] ) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[8]);
} catch (Exception e) {
System.out.println("输出异常信息等其它操作");
} finally {
System.out.println("执行资源释放等相关代码");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 1.3 throw
throw
语句用于创建抛出自定义错误,throw
语句与异常类型一起使用- Java中提供了许多异常类型
ArithmeticException
,FileNotFoundException
,ArrayIndexOutOfBoundsException
,SecurityException
public class Test{
public static void main(String[] args) {
checkValue(-2);
}
static void checkValue(int x) {
if (x < 0) {
throw new ArithmeticException("error is x < 0");
}
else {
System.out.println("x > 0");
}
}
}
/*
Exception in thread "main" java.lang.ArithmeticException: error is x < 0
at com.case_01.Test.checkValue(Test.java:10)
at com.case_01.Test.main(Test.java:5)
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2024/5/31 11:18:42