ITeye博客

构造器异常处理

bd2007 · 2011-08-19 14:10 · java · 编程语言 · Markdown

某些单例模式中的实例需要通过外部资源,如文件,jndi对象进行初始化。 此时可能出现初始化异常,而构造器中不能抛出异常,因此需通过标志位等其它方式进行处理。   果断上代码,有码有真相   1.实例   package com.siyuan.jdktest; import java.io.fileinputstream;import java.io.filenotfoundexception; public class constructorexptest {  private static constructorexptest instance;  private static boolean inited;  private static initexception initexp;  private constructorexptest(string path) {  try {   init(path);   inited = true;  } catch (initexception e) {   initexp = e;  } }  private void init(string path) throws initexception {   try {    fileinputstream finput = new fileinputstream(path);   } catch (filenotfoundexception e) {    throw new initexception("error in constructorexptest init...", e);   }  }  public static final constructorexptest getinstance(string path) throws initexception{  if (instance == null) {   instance = new constructorexptest(path);  }  if (!inited) {   throw initexp;  }  return instance; }  /**  * @param args  * @throws initexception   */ public static void main(string args) throws initexception {  // todo auto-generated method stub  system.out.println(constructorexptest.getinstance("asdfs")); } } class initexception extends exception {  public initexception() {   }  public initexception(string msg) {  super(msg); }  public initexception(throwable cause) {  super(cause); }  public initexception(string msg, throwable cause) {  super(msg, cause); } }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。