常見的執行時異常(RuntimeException) 和 複製中的異常處理
阿新 • • 發佈:2018-12-26
空指標異常: NullPointerException
陣列下標越界異常:ArrayIndexOutOfBoundsException
字串下標越界異常:StringIndexOutOfBoundsException
不合法的引數異常:IllegalArgumentException
算術異常:ArithmeticException
數字格式化異常:NumberFormatException
類造型異常:ClassCastException
複製中自定義異常的處理:
程式碼如下:
自定義一個異常類,其繼承了Excetion類
測試類 程式碼如下:public class CopyException extends Exception{ public CopyException() { super(); } public CopyException(String message, Throwable cause) { super(message, cause); } public CopyException(String message) { super(message); } public CopyException(Throwable cause) { super(cause); } }
public class TestDemo5 { public static void main(String[] args) throws CopyException { FileInputStream fis = null; FileOutputStream fos = null; System.out.println("開始"); try { fis = new FileInputStream("pw.txt"); fos = new FileOutputStream("copy.txt"); int d = -1; while( (d = fis.read())!=-1 ){ fos.write(d); } System.out.println("複製完畢"); } catch (FileNotFoundException e) { //丟擲自定義異常 throw new CopyException("檔案沒有找到",e); } catch (IOException e) { //丟擲自定義異常 throw new CopyException("讀寫異常",e); } finally { if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }