java 异常编码规范
2009年10月18日
没有评论
一直想整理一个java异常的编码规范,但偏偏异常处理可能是编程语言处理中最复杂的话题之一了,我对这方面知识掌握的也不是很全面。但想想作为一个规范来讲,先提供一些最基本的、能达成普遍共识的规范,对于推广还是很有好处的:-),毕竟规范是也是一步一步完善的。如果大家对java异常编码这块有自己的意见和建议的话请留言。
1.避免空的catch和finally块
public void doSomething() { try { FileInputStream fis = new FileInputStream("/tmp/bugger"); } catch (IOException ioe) { // 错误 } finally{//错误 } }
2.不要在Finally块中return,这回导致Exception的丢失。
public class Bar { public String foo() { try { throw new Exception( "My Exception" ); } catch (Exception e) { throw e; } finally { return "A. O. K."; // Very bad. } } }
3.保留StackTrace
在catch块中抛出新的Exception的时候要把原始的Exception传递给新定义的Exception,否则原来的StackTrace就会丢失。
public class Foo { void good() { try{ Integer.parseInt("a"); } catch(Exception e){ throw new Exception(e); } } void bad() { try{ Integer.parseInt("a"); } catch(Exception e){ throw new Exception(e.getMessage()); } } }
4. 避免在finally块中再次抛出异常
public class Foo { public void bar(){ try { // Here do some stuff } catch( Exception e) { // Handling the issue } finally { // is this really a good idea ? throw new Exception(); } } } }
