1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class CH01201 { public static void main(String[] args) { int i = 50 / 0 ; //ArithmeticException //String s = null ; //System . out . println (s.length ()) ; //NullPointerException //int a [] = new int [5] ; //a [10] = 50 ; //ArrayIndexOutOfBoundsException } } |
有些情況是無法進入例外處理的,比如作業系統的或是設備發生問題。
try • catch
所有異常和錯誤類型都是「Throwable」類的子類,都是在「執行階段」發生。一個分支以「Exception」為結尾,通常為程式執行中無預期發生如「NullPointerException」。另一個分支以「Error」為結尾,通常為「JVM」環境的限制如「 StackOverflowError」。這2種解釋都太過抽象,若用較為實際的方式則分為3種類型。1) Checked Exception
執行階段發生的異常狀況,能透過修改程式解決的異常:「IOException、SQLException...」。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import java.io.IOException; public class CH01202 { public static void main(String[] args) { Process p = null ; while ( true ) { try { // p = Runtime.getRuntime().exec("wmic cpu get loadpercentage"); p = Runtime.getRuntime().exec( "wmc cpu get loadpercentage" ); // 可以透過修改程式碼解決異常 System.out.println( "正確執行" ); } catch (IOException e) { System.out.println( "捕捉到問題: " +e); break ; } } } } |
2) Unchecked Exception
同樣是執行階段發生的異常狀況,不同之處在於沒有辦法透過修改程式解決:「ArithmeticException、NullPointerException、ArrayIndexOutOfBoundsException...」。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class CH01203 { public static void main(String[] args) { int i[] = { 1 , 2 , 3 , 4 }; //System.out.println(i[4]); try { System.out.println(i[ 4 ]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println( "成功捕捉: " +e); } } } |
3) Error
完全沒辦法避免的,例如「OutOfMemoryError、VirtualMachineError、AssertionError」。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class CH01204 { public static void main(String[] args) { try { System.out.printf( "執行 %s 功能%n" , args[ 0 ]); } catch (Exception e) { System.out.println( "沒有指定參數!" ); //e.printStackTrace(); } finally { System.out.println( "執行完成..." ); } } } |
catch(Exception e)可以捕捉到所有問題,但是只會提示第1個。使用上很方便,但是沒有辦法精確處理不同問題。
連續偵測例外
可以根據可能出現的各種例外建立處理機制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.IOException; public class CH01205 { public static void main(String[] args) { Process p = null ; while ( true ) { try { // p = Runtime.getRuntime().exec("wmic cpu get loadpercentage"); p = Runtime.getRuntime().exec( "wmc cpu get loadpercentage" ); // 可以透過修改程式碼解決異常 System.out.println( "正確執行" ); } catch (IOException e) { System.out.println( "捕捉到問題: " +e); break ; } catch (Exception e) { System.out.println( "捕捉到其他問題" +e); break ; } } } } |
強制拋出例外
可以根據自己的喜好拋出不同的種類的例外1 2 3 4 5 6 7 8 9 10 11 12 13 | public class CH01206 { public static void main(String[] args) { if (args != null ) { throw new NullPointerException( "query is null" ); } } } |
沒有留言:
張貼留言