這篇文章主要介紹Java中try catch如何處理異常,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
public class TryCatchStu {
/*try catch:自己處理異常
*try{
* 可能出現異常的代碼
*}catch(異常類名A e){
* 如果出現了異常類A類型的異常,那么執行該代碼
*}...(catch可以有多個)
*finally{
* 最終肯定必須要執行的代碼(例如釋放資源的代碼)
*}
*1.try內的代碼從出現異常的那一行開始,中斷執行
*2.執行對應的catch塊內的代碼
*3.繼續執行try catch 結構之后的代碼
*1.如果catch內的異常類存在子父類的關系,那么子類應該在前,父類在后
*2.如果finally中有return語句,那么最后返回的結果肯定以finally中的返回值為準
*3.如果finally語句中有return,那么沒有被處理的異常將會被吞掉
*1.兒子不能比父親的本事大
*2.兒子要比父親開放
*3.兒子不能比父親惹更大的麻煩(子類的異常的類型不能是父類的異常的父類型)
*1.getMessage():獲取異常描述信息字符串
*2.toString():返回異常類的包路徑和類名和異常描述信息字符串
*3.printStackTrace():除了打印toString的信息外,還要打印堆棧信息
*/
public static void main(String[] args) { System.out.println(demo()); } public static int demo(){ GirlHome gh = new GirlHome("小陳陳",'男',28); try{ gh.intoHome(); System.out.println("進入了女生宿舍"); return 0; }catch(SexOutException e){ //System.out.println("出現了異常"); //System.out.println(e); e.demo(); e.printStackTrace(); }catch (AgeOutException e) { // TODO: handle exception }finally{ System.out.println("我必須被執行"); } return 1; //System.out.println("愉快的一天結束啦"); } class GirlHome { public String name; public char sex; public int age; public GirlHome(String name,char sex,int age) { super(); this.name = name; this.sex = sex; this.age = age; } //如果發現進入者是男的,那么拋出性別異常 public void intoHome() throws SexOutException,AgeOutException{ if(sex!='女'){ SexOutException se = new SexOutException(name+"你不是女的,滾!!!"); throw se; } if(age>25){ throw new AgeOutException(name+"你的年齡太大了,滾!!!!"); } System.out.println(name+"開心的進入了宿舍"); } public void demo()throws Exception{} } class SmallGirlHome extends GirlHome{ public SmallGirlHome(String name, char sex, int age) { super(name, sex, age); // TODO Auto-generated constructor stub } @Override public void intoHome() throws SexOutException,AgeOutException { } public void demo() { } class AgeOutException extends Exception{ public AgeOutException(String message){ super(message); } } class SexOutException extends Exception{ public SexOutException(String message){ super(message); } public void demo(){ System.out.println("愛啦啦阿拉"); } }
以上是“Java中try catch如何處理異?!边@篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。