异常处理的动手动脑
一,拋異常的類型
拋異常:1,Error錯誤,系統錯誤 2,Exception錯誤
Exception類又包括:RuntimeException非檢查異常和檢查異常。
Error例子: 1.AssertionError程序運行期間判斷某個條件是否滿足
,不滿足時,拋出AssertionError。
???????????????? 2.OOM Error系統內存不足。
二,小探索
int i=1, j=0, k;
k=i/j;
javac生成idiv字節碼指令
double d1=100,d2=0,result;
?? ?result=d1/d2;
System.out.println("浮點數除以零:" + data);
浮點數除以0:Infinity
javac生成ddiv字節碼指令,JVM在具體實現這兩個指令時,采用了不同的處理策略,導致兩段代碼運行時得到不同的結果。
三,try catch的嵌套
public class CatchWho { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch"); }throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("發生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch"); } } }ArrayIndexOutOfBoundsException/內層try-catch 發生ArithmeticException
上述是結果
public class CatchWho2 { public static void main(String[] args) { try {try { throw new ArrayIndexOutOfBoundsException(); } catch(ArithmeticException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch"); }throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("發生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch"); } } } ArrayIndexOutOfBoundsException/外層try-catch看下面這段代碼,
public class EmbededFinally {public static void main(String args[]) {int result;try {System.out.println("in Level 1");try {System.out.println("in Level 2");//result=100/0; //Level 2try {System.out.println("in Level 3");result=100/0; //Level 3 } catch (Exception e) {System.out.println("Level 3:" + e.getClass().toString());}finally {System.out.println("In Level 3 finally");}// result=100/0; //Level 2 }catch (Exception e) {System.out.println("Level 2:" + e.getClass().toString());}finally {System.out.println("In Level 2 finally");}// result = 100 / 0; //level 1 } catch (Exception e) {System.out.println("Level 1:" + e.getClass().toString());}finally {System.out.println("In Level 1 finally");}}}運行結果為
in Level 1 in Level 2 in Level 3 Level 3:class java.lang.ArithmeticException In Level 3 finally In Level 2 finally In Level 1 finally當有多層嵌套的finally時,異常在不同的層次拋出?? ?,在不同的位置拋出,會導致不同的finally語句塊執行順序。
四,自定義異常
Class MyException extends Exception
?? ?{ …??? }
Class MyClass {
?? ??? ?void someMethod() {
?? ??? ??? ?if (條件) throw new MyException();
?? ??? ?}
?? ?}
轉載于:https://www.cnblogs.com/xcl666/p/9938913.html
總結
- 上一篇: JAVA学习笔记系列4-Eclipse版
- 下一篇: NOIP2018复赛 游记