12.10 构造器

来源:互联网 发布:淘宝店铺打客服电话 编辑:程序博客网 时间:2024/06/09 21:45

当构造函数会抛出异常时, 需要在对象生成时候进行try catch, 此外, 对于类似文件打开等产生资源, 并且最后需要关闭的, 要在打开资源后使用 try finally方式添加资源关闭代码

package com.cnsuning.src;public class DemoFile {public DemoFile(String fileName) throws Exception {// TODO Auto-generated constructor stubthis.openFile(fileName);}private void openFile(String fileName) throws Exception {if (0 == fileName.compareTo("")) {throw new Exception("file open error");}System.out.println("open file");}public void closeFile() {System.out.println("close file");}public String getLine(){return "one line";}public static void main(String[] args) {// TODO Auto-generated method stub}}package com.cnsuning.src;public class Main {public Main() {// TODO Auto-generated constructor stub}public static void main(String[] args) {try {String fileName = "";DemoFile dFile = new DemoFile(fileName);try{dFile.getLine();dFile.closeFile();}finally{dFile.closeFile();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

java.lang.Exception: file open errorat com.cnsuning.src.DemoFile.openFile(DemoFile.java:12)at com.cnsuning.src.DemoFile.<init>(DemoFile.java:7)at com.cnsuning.src.Main.main(Main.java:12)

0 0