Java异常
Kang Lv3

异常

Java异常

error

Error描述了Java运行时系统的内部错误和资源耗尽错误,如堆溢出和栈溢出

堆溢出:OutOfMemoryError

  • 如果虚拟机在扩展栈时无法申请到足够的空间,则抛出此异常

栈溢出:StackOverFlowError

  • 如果线程请求的栈深度大于虚拟机所允许的深度,就会抛出此异常

excption

Exception分为运行时(RunTimeException)和其他异常(IOException/SqlException)

RunTimeException:NullPointerException,ArithmeticException,IndexOutOfBoundsException

受检异常和非受检异常

非受检异常:指编译期免检异常,包括派生于Error或RunTimeException类的所有异常。
受检异常:指编译时强制检查的异常,包括非受检异常的所有的其他异常。

异常处理

异常处理的本质是抛出异常和捕获异常

Java的异常处理是通过5个关键词来实现的:try、catch、throw、throws和finally。

  1. try用来指定一块预防所有异常的程序。
  2. catch子句紧跟在try块后面,用来指定你想要捕获的异常的类型;
  3. throw语句用来明确地抛出一个异常;
  4. throws用来声明一个方法可能抛出的各种异常;
  5. finally为确保一段代码不管发生什么异常状况都要被执行,在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if (name == null) {
throw new NullPointerException;
}

public void info() throws Exception {
// 程序语句
}

try {
// 程序语句
} catch(ArithmeticException e) {
// 程序语句
} finally {
// 程序语句
}

其中finally一定是会执行的
如果try中没有异常,就按照try-finally执行
如果try中有异常,就执行到try中有异常的位置,然后执行catch,最后执行finally

try-catch-finally中有return

try中有return

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class trycatch {
public static void main(String[] args) {
trycatch tc = new trycatch();
int re = tc.testtrycatch();
System.out.println("return" + re);
}

private int testtrycatch() {
int i = 1;
try {
i++;
System.out.println("try" + i);
return i;
} catch (Exception ex) {
i++;
System.out.println("catch" + i);
} finally {
i++;
System.out.println("finally" + i);
}
return i;
}
}

输出:
try2
finally3
return2

catch中有return

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class trycatch {
public static void main(String[] args) {
trycatch tc = new trycatch();
int re = tc.testtrycatch();
System.out.println("return" + re);
}

private int testtrycatch() {
int i = 1;
try {
i++;
System.out.println("try" + i);
int x = i/0;
} catch (Exception ex) {
i++;
System.out.println("catch" + i);
return i;
} finally {
i++;
System.out.println("finally" + i);
}
return i;
}
}

输出:
try2
catch3
finally4
return3

finally中有return

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class trycatch {
public static void main(String[] args) {
trycatch tc = new trycatch();
int re = tc.testtrycatch();
System.out.println("return" + re);
}

private int testtrycatch() {
int i = 1;
try {
i++;
System.out.println("try" + i);
int x = i/0;
} catch (Exception ex) {
i++;
System.out.println("catch" + i);
return i;
} finally {
i++;
System.out.println("finally" + i);
return i;
}
}
}

输出:
try2
catch3
finally4
return4

执行顺序:先执行try和catch中return之前的语句,然后暂时保存return的值,等执行完finally之后,再返回之前保存的return的值。
如果finally中包含return语句,则前面try和catch中的return失效,但是不推荐这样写。

  • 本文标题:Java异常
  • 本文作者:Kang
  • 创建时间:2021-04-10 14:50:10
  • 本文链接:ykhou.github.io2021/04/10/Java异常/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!