您好,登錄后才能下訂單哦!
這篇文章主要介紹Java開發(fā)過程中異常處理問題的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
我這里是因為:arr[3]不存在:
java.lang.ArrayIndexOutOfBoundsException: 3
public class btyf { public static void main(String[] args){ int[] arr={1,2,3}; System.out.println(arr[0]); System.out.println(arr[3]); System.out.println(arr[1]); //1 異常 ArrayIndexOutOfBoundsException 異常名 // btyf.main(btyf.java:13) 異常位置第13行 // //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 // at btyf.main(btyf.java:13) } }
結(jié)果:
java虛擬機:會把異常內(nèi)容輸出控制臺
public class btyf { public static void main(String[] args){ int[] arr={1,2,3}; System.out.println(arr[0]); try{ System.out.println(arr[3]); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("你訪問的數(shù)組索引不存在"); e.printStackTrace(); //輸出異常數(shù)據(jù):控制臺 } System.out.println(arr[1]); //1 異常 // ArrayIndexOutOfBoundsException 異常名 // btyf.main(btyf.java:13) 異常位置 //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 // at btyf.main(btyf.java:13) } }
結(jié)果:
通過try抓異常,后面沒有異常的代碼就不會因為前面的代碼一些異常而停止,
就可以執(zhí)行
System.out.println(e.toString());//打印出異常內(nèi)容:位置和名稱
e.printStackTrace(); //輸出異常數(shù)據(jù):控制臺
System.out.println(e.getMessage()); 一樣
多用:System.out.println(e.toString());這個
try{ System.out.println(arr[3]); }catch (ArrayIndexOutOfBoundsException e) { //System.out.println("你訪問的數(shù)組索引不存在"); // e.printStackTrace(); System.out.println(e.getMessage()); //public String getMessage() { // return detailMessage; // } System.out.println(e.toString()); }
結(jié)果:
但是在異常處:還是要添加try catch
添加位置:異常成員方法public static void main(String[] args)throws ArrayIndexOutOfBoundsException{}
代碼:
public class uytig { public static void main(String[] args)throws ArrayIndexOutOfBoundsException{ int[] arr={1,2,3}; System.out.println(arr[0]); try { System.out.println(arr[3]); } catch (Exception e) { e.printStackTrace(); } System.out.println("執(zhí)行中"); } }
以上是“Java開發(fā)過程中異常處理問題的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。