一些印象不是很深刻的东东
1、finallya、就算try里面有catch没有捕获到的异常,finally也会被执行!b、java异常处理的bug
public class LostMessage(){ void f() throws VeryImportantException{ throw new VeryImportantException(); } void dispose() throws HoHumException{ throw new HoHumException(); } public static void main(String [] args) throws Exception{ LostMessage lm = new LostMessage(); try { lm.f(); } finally { lm.dispose(); // VeryImportantException 消失了,被HoHumException取代 } }}2、加在异常上面的限制
a、覆写方法的的时候,你只能抛出这个方法在基类中的版本所声明的异常。[多态]b、派生类可能以任何方式调用基类的构造函数,派生类的构造函数不能捕捉到基类构造函数的任何异常,所以派生类也必须显式声明基类可能抛出的任何异常c、基类方法抛出异常,但是在派生类覆盖该方法时中可以不抛出异常d、打开文件一个方法,FileNotFoundException 在new 时抛出。可以判断文件打没打开,[注意构造函数]
class InputFile { private BufferedReader in; public InputFile(String fname) throws Exception { try { in = new BufferedReader( new FileReader(fname)); // Other code that might throw exceptions } catch (FileNotFoundException e) { System.err.println( " Could not open " + fname); // Wasn't open, so don't close it throw e; } catch (Exception e) { // All other exceptions must close it try { in.close(); } catch (IOException e2) { System.err.println( " in.close() unsuccessful " ); } throw e; // Rethrow } finally { // Don't close it here!!! } } public String getLine() { String s; try { s = in.readLine(); } catch (IOException e) { throw new RuntimeException( " readLine() failed " ); } return s; } public void dispose() { try { in.close(); System.out.println( " dispose() successful " ); } catch (IOException e2) { throw new RuntimeException( " in.close() failed " ); } }}注:dispose()不要放在finalize()中,因为finalize是否会被调用以及什么时候调用你都不知道!
3、异常的匹配a、抛出的派生类异常能被基类捕捉
4、原则"除非知道该怎样去处理异常,否则别去捕捉"