Java异常机制
异常机制 Exception
/** * user try/catch/final */ public class Test { public void openFile(){ try { FileReader fr = new FileReader("d:/test.txt"); int a = fr.read(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { System.out.println("finally works!"); } } }
/** * use throws, 用throws的时候, 直接声明且抛出异常, 在方法具体被调用的地方做处理 */ public class Test { public String openFile() throws FileNotFoundException, IOException { FileReader fr = new FileReader("d:/test.txt"); char c = (char)fr.read(); return "" +c; } public static void main(String[] args) { String str; try { str = new Test().openFile(); //调用方法时候做具体处理 } catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e ){ e.printStackTrace(); }finally { System.out.println("okay..."); } } }
浙公网安备 33010602011771号