幾種常見的RuntimeException例子
阿新 • • 發佈:2018-12-26
public class ExceptionTest { public static void main(String[] args) { //常見的RuntimeException //1.ArithmeticException()運算異常 //2.ClassCastException()類的轉換異常 //3.NullPointerException()空指標異常 //4.IndexOutOfBoundsException()陣列指標越界異常 try{ int i=10; int j = 0; System.out.println(i/j); }catch(ArithmeticException e){ System.out.println("除數不能為0"); } FileReader fr = null; try { fr = new FileReader("f:/test/dd/tt.txt"); } catch (FileNotFoundException e) {//這個是IO異常,不是RuntimeException異常 System.out.println("找不到檔案"); // e.printStackTrace(); } finally{ try { fr.close(); }catch(IOException i){ } catch (NullPointerException n) { System.out.println("空指標異常"); } } try{ int[] aa = {1,2,3}; System.out.println(aa[3]); }catch(IndexOutOfBoundsException e){ System.out.println("陣列越界!"); } Map<String,String> map=new HashMap<String, String>(); try{ TreeMap<String ,String> map2=(TreeMap)map; }catch(ClassCastException c){ System.out.println("類轉換異常"); } //自定義異常 try{ Person p = new Person(-1); }catch(MyException m){ m.printStackTrace(); } } }