標籤:
java中異常
- 異常Exception 是我們可以處理的,可以進行補救,遇到異常就不會執行了?
-
package cn.seven.shengsiyuan.exception;/* * Time:2015年04月05日12:24:58,清明節 * Location:501 * */public class ExceptionDemo1 {public static void main(String[] args) {// TODO Auto-generated method stubint a = 3;int b = 0;int c = a / b;//這句話執行會發生異常,下面的語句便不執行System.out.println("------");System.out.println(c);}}
/*
Exception in thread "main" java.lang.ArithmeticException: / by zero
at cn.seven.shengsiyuan.exception.ExceptionDemo1.main(ExceptionDemo1.java:17)
*/
- 異常的繼承體系-java中的異常都繼承自Exception類異常分為兩大類:
Checked Exception(非運行時異常 )
UnChecked Exception(運行時異常 Runtime Exception)
java.langClass Throwable java.lang.Object java.lang.Throwable All Implemented Interfaces: Serializable Direct Known Subclasses: Error, Exception
java.langClass Exception java.lang.Object java.lang.Throwable java.lang.Exception
-
- 運行時異常 RuntimeException
java.lang.Object java.lang.Throwable- java.lang.Exception java.lang.RuntimeException javax.management.JMRuntimeException
- 非運行時異常: 繼承了Exception類,但是不繼承RuntimeException類的異常
- RuntimeException 異常的處理-固定的流程和模式
-
try{}catch(Exception e){}
-
package cn.seven.shengsiyuan.exception;/* * Time:2015年04月05日12:24:58,清明節 * Location:501 * */public class ExceptionDemo1 {public static void main(String[] args) {// TODO Auto-generated method stubint c = 0;try{int a = 3;int b = 2; c= a / b; System.out.println("---hello---");}catch(ArithmeticException e){//將19行產生的異常對象賦值給了ee.printStackTrace();//printStackTrace列印異常的資訊,來自Throwable類的方法}finally{System.out.println("finally");}System.out.println("------");System.out.println(c);}}/* * 19行出現異常,產生針對於該異常類的對象 ArithmeticException * 當異常發生的時候,進入catch塊,由catch進行接管,然後執行catch塊中的內容 * 執行完畢,接下來執行syso語句 * * * 現在的重點便是21行-的catch語句的過程 */
- 完整的異常處理結構
try{//可能發生異常的語句的代碼塊}catch(異常對象){//對發生異常之後的處理}finally{//無論是否發生異常,最終都會被執行的語句,防止某些語句因為發生了異常而無法得到執行}
package cn.seven.shengsiyuan.exception;/* * Time:2015年04月05日12:24:58,清明節 * Location:501 * */public class ExceptionDemo1 {public static void main(String[] args) {// TODO Auto-generated method stubint c = 0;try{int a = 3;int b = 0; c= a / b; System.out.println("---hello---");}catch(ArithmeticException e){e.printStackTrace();//printStackTrace列印異常的資訊,來自Throwable類的方法}finally{System.out.println("finally");//一定會被執行,無論是否發生異常}//System.out.println(c);?疑問的是為什麼這邊會仍然輸出的是 c=0?是因為c=a/b;語句出現異常,c沒有執行指派陳述式}}
- 程式中出現多個異常的話,只會有特定的catch處理特定的異常
Think in Java 筆記_Chapter12_1_Exception基礎_繼承和RuntimeException處理1