构造器异常处理

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值