JAVA总结之异常

问题描述:

  异常,是Java必须懂的知识点,今天总结了一下。异常可以分为:

    1.捕获异常try{可能出现异常的代码}:当try出现异常时,try语句块异常行之后代码将不执行,直接跳转到catch

    2.处理异常catch{根据try语句块中出现异常,JVM将查找相应的第一个匹配catch语句}

    3.抛出异常throw new Exception(String str):之后的代码将全部不执行,直接跳出方法。

    4.finally不管是return,break,throw new Excetion都会执行。

  异常几个属性和常用对应的方法:

    1.String message;出现异常的信息,getMessage();

    2.StackTraceElement[] StackTrace;异常栈跟踪,引发异常的所有方法调用记录。常用printStackTrace()

    3.Throwable cause;产生异常的原因,getCause();

  异常注意点:

    1.由于try语句需要JVM一直监控,会非常消耗资源,降低系统的效率,所以尽量减少try语句块的代码量;

    2.如果某个方法抛出异常,则调用这个方法的方法需要捕获异常

测试代码:

 1 package com.test;
 2 
 3 public class ExceptionTest {
 4 
 5     /**
 6      * 异常总结
 7      */
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         try {
11             testThrowException();
12         } catch (Exception e) {
13             // TODO Auto-generated catch block
14             e.printStackTrace();
15         }
16     }
17     
18     public static void testThrowException() throws Exception{
19         //由于抛出异常,所以调用这个方法的方法要抛异常
20         int flag = 1;
21         try{
22             flag = 2;
23             flag = 3/0;
24             System.out.println("testThrowException.try.flag = " + flag);
25         }catch(Exception e){
26             System.out.println("testThrowException.catch.flag = " + flag);
27             System.out.println("e.getMessage() : " + e.getMessage());
28             System.out.println("e.getCause() : " + e.getCause());
29             e.printStackTrace();
30             throw new Exception("testThrowException()异常," + e.getMessage());
31         }finally{
32             System.out.println("这个是不管怎样都执行的finally;");
33         }
34         System.out.println("testThrowException.flag = " + flag);
35     }
36 }

控制台输出:

testThrowException.catch.flag = 2
e.getMessage() : / by zero
e.getCause() : null
java.lang.ArithmeticException: / by zero
    at com.test.ExceptionTest.testThrowException(ExceptionTest.java:23)
    at com.test.ExceptionTest.main(ExceptionTest.java:11)
这个是不管怎样都执行的finally;
java.lang.Exception: testThrowException()异常,/ by zero
    at com.test.ExceptionTest.testThrowException(ExceptionTest.java:30)
    at com.test.ExceptionTest.main(ExceptionTest.java:11)
原文地址:https://www.cnblogs.com/atp-sir/p/6397538.html