Java基礎(chǔ)異常處理代碼及原理解析
這篇文章主要介紹了java基礎(chǔ)異常處理代碼及原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
異常的定義:中斷了正常指令流的事件。
try..catch..finally結(jié)構(gòu):
class Test{ public static void main(String[] args){ System.out.println(1); try{ System.out.println(2); int i = 1 / 0; System.out.println(3); } catch(Exception e){ e.printStackTrace(); System.out.println(4); } finally{ System.out.println(5); } System.out.println(6); } }
輸出結(jié)果:
D:\Java\code\練習(xí)十二>java Test java.lang.ArithmeticException: / by zero at Test.main(Test.java:6)
throw與throws關(guān)鍵字
class User{ private int age; public void setAge(int age) throws Exception{ if(age <= 0){ Exception e = new Exception("input age is error!"); throw e; } else{ this.age=age; } } }
class Test{ public static void main(String[] args){ User u = new User(); try{ u.setAge(-20); } catch(Exception e){ System.out.println(e); } } }
D:\Java\code\練習(xí)十二>java Test java.lang.Exception: input age is error!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決get請求入?yún)NotNull驗(yàn)證不生效問題
這篇文章主要介紹了解決get請求入?yún)NotNull驗(yàn)證不生效問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09redis setIfAbsent和setnx的區(qū)別與使用說明
這篇文章主要介紹了redis setIfAbsent和setnx的區(qū)別與使用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08Mysql?json類型字段Java+Mybatis數(shù)據(jù)字典功能的實(shí)踐方式
這篇文章主要介紹了Mysql?json類型字段Java+Mybatis數(shù)據(jù)字典功能的實(shí)踐方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08springboot?整合表達(dá)式計(jì)算引擎?Aviator?使用示例詳解
本文詳細(xì)介紹了Google?Aviator?這款高性能、輕量級的?Java?表達(dá)式求值引擎,并通過詳細(xì)的代碼操作演示了相關(guān)API的使用以及如何在springboot項(xiàng)目中進(jìn)行集成,感興趣的朋友一起看看吧2024-08-08