在Java中读取属性文件时,我应该使用try-catch还是抛出自定义异常或两者兼而有之?

时间:2015-09-08 12:32:58

标签: java exception-handling

我正在从项目的类路径中的属性文件中读取属性。

public Properties readFileFromClasspath(String fileName) throws MyException {

    Properties props = new Properties();
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
    if (inputStream != null) {
        try {
            props.load(inputStream);
        } catch (IOException e) {
            throw new MyException("Could Not read properties from file  : [" + fileName + "].",e);
        }
    } else {

        throw new MyException("Could Not find property file  : [" + fileName + "] in the classpath.");
    }
    return mainProperties;

 }

此处MyException只是扩展Exception

我应该使用 try-catch 还是抛出MyException 两者

4 个答案:

答案 0 :(得分:0)

取决于。如果有异常,您可以加载默认属性吗?在这种情况下,捕获异常,加载默认属性并在日志中发出警告。

如果无法加载没有属性的应用程序,则必须抛出异常。

您必须决定是否可以控制您的例外情况。

答案 1 :(得分:0)

我认为你可以自由选择,但在这两种情况下,你应该在投掷时尽可能多地提供信息。在这种情况下,我认为没有理由创建自定义异常。如果在读取属性文件时发生错误,我会抛出IOException,否则FileNotFoundException如果属性文件不存在则抛出Thank you dear **jlhoward** for your well detailed answer. I found a solution to my problem and here is the script that I used: Folder="C:/cru2/Pre/" file=paste(folder,"Precipitation_1901-2014.txt",sep="") data=read.table(file,header=T,sep="\t") years=1901:2014 cumulyears=data[,1:2] nyr=0 n2=2 for (yrs in annees){ nyr=nyr+1 n1=n2+1 n2=n1+11 datayrs=cbind(data[,1:2],data[,n1:n2]) output=paste(folder,yrs,".txt",sep="") write.table(datayrs, file = output, append = FALSE,sep = "\t",eol = "\r", na = "NA", dec = ".", row.names = F,col.names = F) row.sums <- apply(data[,n1:n2], 1, sum,na.rm=T) cumulyears=cbind(cumulyears,row.sums) } colnames(cumulyears)=c("Latitude","Longitude",years) output=paste(folder,"precipitationyears.txt",sep="") write.table(cumulyears, file = output, append = FALSE,sep = "\t",eol = "\r", na = "NA", dec = ".", row.names = F,col.names = T) I did not try yet what you have proposed but I will do so in a brief delay inshAllah. About your question on how I have converted a ".nc" to ".txt" below is the script I have used. Here is also the Climate Research Unit link where I got my data (http://www.cru.uea.ac.uk/cru/data/hrg/cru_ts_3.23/cruts.1506241137.v3.23/). Thanks again. library("ncdf") library("chron") Folder="C:/cru2" variable="pre" periodes1=c(1901,1911,1921,2011) periodes2=c(2014,1920,1930,2014) nbyrs=length(periodes1) for (ip in 1:1){ name=paste("cru_ts3.23.",periodes1[ip],".",periodes2[ip],".",variable,".dat",sep="") years=c(periodes1[ip],periodes2[ip]) file=paste(folder,name,".nc",sep="") x <- open.ncdf("cru_ts3.23.1901.2014.pre.dat.nc") mrlon_t = get.var.ncdf(x,"lon") #Longitude mrlat_t = get.var.ncdf(x,"lat") #Latitude lonmin=-18 lonmax=26 latmin=3.4 latmax=17 mrlon=mrlon_t[mrlon_t>=lonmin&mrlon_t<=lonmax] lon=length(mrlon) lo1=which(mrlon_t==mrlon[1]) mrlat=mrlat_t[mrlat_t>=latmin&mrlat_t<=latmax] lat=length(mrlat) la1=which(mrlat_t==mrlat[1]) mpr= get.var.ncdf(x,varid=variable,start=c(lo1,la1,1),count=c(lon,lat,-1)) mrtime=get.var.ncdf(x,"time") mrtime=mrtime/86400 #dim1=c(dim(matrice)) ts=length(mrtime) print(paste("Nb days ",ts,sep="")) date1=paste(years[1],"-01-01",sep="") date2=paste(years[2],"-12-31",sep="") date=seq(as.Date(date1), as.Date(date2), "months") #for (t in 1:ts) {date[t]<-t} d1=lon*lat+1 d2=ts+2 mpr_sortie = array(NA, c(d1,d2)) mpr_sortie[1,1]="latitude" mpr_sortie[1,2]="longitude" for (t in 1:ts) {mpr_sortie[1,t+2]<-as.character(date[t])} for (la in 1:lat) { for (lo in 1:lon) { row=(la-1)*lon+lo+1 mpr_sortie[row,1]<-mrlat[la] mpr_sortie[row,2]<-mrlon[lo] for (t in 1:ts) { rcol=t+2 mpr_sortie[row,rcol]<-mpr[lo,la,t] } } } file=paste(folder,name,".txt",sep="") write.table(mpr_sortie, file = "file", append = FALSE, sep ="\t", eol = "\r", na = "NA", dec = ".", row.names =FALSE, col.names =FALSE) }#End for 。如果您想阅读更多内容,here是您可以找到的有关异常处理的众多教程之一。

答案 2 :(得分:0)

我认为有时我们会用异常来做,对我来说,你的代码应该只验证文件是否存在并抛出FileNotFoundException,除了为什么抛出已抛出的异常?你没有做任何特别的事情。

答案 3 :(得分:0)

假设您在启动期间从固定名称属性文件加载应用程序属性,我会抛出未声明的未经检查的异常:

    public void readApplicationProperties() {
        this.properties = readFileFromClasspath("application.properties");
    }

    private Properties readFileFromClasspath(String fileName) {
        Properties props = new Properties();
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
        if (inputStream == null) {
            throw new RuntimeException("Could not find property file: [" + fileName + "] in the classpath.");
        }
        try {
            props.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("Could not read properties from file: [" + fileName + "].", e);
        }
        return props;
    }

我的理由是应用程序无法从此错误中恢复,因此没有必要创建自定义检查异常,捕获它等等。最后,应用程序必须以有意义的错误消息终止。最简单的方法是使用未经检查的异常。