这篇文章主要介绍了java抛出异常的几种情况小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
这篇文章主要介绍了java抛出异常的几种情况小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
这篇文章主要介绍了java抛出异常的几种情况小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
1
2
3
4
5
6
|
//代码1 public static void test() throws Exception { throw new Exception( "参数越界" ); System.out.println( "异常后" ); //编译错误,「无法访问的语句」 } |
1
2
3
4
5
6
7
|
//代码2 try { throw new Exception( "参数越界" ); } catch (Exception e) { e.printStackTrace(); } System.out.println( "异常后" ); //可以执行 |
1
2
3
4
5
|
//代码3 if ( true ) { throw new Exception( "参数越界" ); } System.out.println( "异常后" ); //抛出异常,不会执行 |
总结 :
另外总结一下运行时异常与非运行时异常的区别:
1
2
3
4
|
public static void test() throws Exception { throw new Exception( "参数越界" ); System.out.println( "异常后" ); //编译错误,「无法访问的语句」 } |
1
2
3
4
5
6
7
8
|
//代码2 //异常被捕获,日志打印了异常,代码继续执行 try { throw new Exception( "参数越界" ); } catch (Exception e) { e.printStackTrace(); } System.out.println( "异常后" ); //可以执行 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//psvm 快捷键 public static void main(String[] args) { try { test(); } catch (Exception e) { e.printStackTrace(); } } public static void test() throws Exception { //代码3 if ( true ) { throw new Exception( "参数越界" ); } System.out.println( "异常后" ); //抛出异常,不会执行 } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public static void test() throws Exception { //代码4 try { int i= 1 / 0 ; } catch (Exception e) { e.printStackTrace(); throw new Exception( "代码执行异常后打印并抛出异常提示" ); } System.out.println( "异常后" ); //抛出异常,不会执行 } //打印日志 java.lang.ArithmeticException: / by zero at zmc.eter.etern.text.text.test(text.java: 23 ) at zmc.eter.etern.text.text.main(text.java: 14 ) java.lang.Exception: 代码执行异常后打印并抛出异常提示 at zmc.eter.etern.text.text.test(text.java: 26 ) at zmc.eter.etern.text.text.main(text.java: 14 ) |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持米米素材网。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/Cjava_math/article/details/102728356
发表评论