---
title: "构造器异常处理"
author: "bd2007"
date: "2011-08-19T14:10:43Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-08-19T14:10:43Z"
id: 1153354
url: "https://bd2007.iteye.com/blog/1153354"
---

某些单例模式中的实例需要通过外部资源，如文件，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>}