如何更改此设置以使其失败?

时间:2017-06-07 01:22:54

标签: java file csv error-handling opencsv

我认为如果遇到任何错误,则以下代码会停止。

public static void exportDatapointsToCSV(List<Datapoint> datapointList, File exportDir) {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy (h:mm a)", Locale.US);
    File file = new File(exportDir, "my_datapoints.csv");

    try {
        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        csvWrite.writeNext(new String[]{"DATAPOINT_LABEL", "VALUE", "TIMESTAMP", "TIMESTAMP_FORMATTED", "NOTE"});

        for (Datapoint datapoint : datapointList) {
            String arrStr[] = new String[]{
                    datapoint.getLabel(),
                    datapoint.getValue() + "",
                    datapoint.getTimestamp() + "",
                    sdf.format(new Date(datapoint.getTimestamp())) + "",
                    datapoint.getNote()
            };
            csvWrite.writeNext(arrStr);
        }
        csvWrite.close();
    }
    catch (Exception sqlEx) {
        Log.e(LOG_TAG, sqlEx.getMessage(), sqlEx);
    }
}

但我希望它:

  1. 如果无法创建文件,请抛出错误并停止。

  2. 如果它在给定行上遇到错误,请记录它但移到下一行,而不是停止整个行。

  3. 我只是将try / catch移动到循环中吗?这涵盖了吗?

2 个答案:

答案 0 :(得分:1)

您捕获的异常是所有异常的祖父 - 如果您查看javadocs,您会看到构造函数new FileWriter(file)抛出IOException

因此,如果您想要某些行动,例如如果失败则记录和退出然后尝试

 CSVWriter csvWrite = null;
 try {
         csvWrite = new CSVWriter(new FileWriter(file));
 } catch (IOException ex) {
    Log.e(LOG_TAG, ex.getMessage(), ex);
    return; // or System.exit or what either
 }

答案 1 :(得分:0)

如果我在代码中显示正确的话会更好:

public static void exportDatapointsToCSV(List<Datapoint> datapointList, File exportDir) {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy (h:mm a)", Locale.US);

    File file = null;
    try{ ( file = new File(exportDir, "my_datapoints.csv") ).createNewFile(); }
    catch(IOException e){throw new RuntimeException(e); }

    CSVWriter csvWrite = null;
    try {
        csvWrite = new CSVWriter(new FileWriter(file));
        csvWrite.writeNext(new String[]{"DATAPOINT_LABEL", "VALUE", "TIMESTAMP", "TIMESTAMP_FORMATTED", "NOTE"});

        for (Datapoint datapoint : datapointList) {
            String arrStr[] = new String[]{
                    datapoint.getLabel(),
                    datapoint.getValue() + "",
                    datapoint.getTimestamp() + "",
                    sdf.format(new Date(datapoint.getTimestamp())) + "",
                    datapoint.getNote()
            };
            try{ csvWrite.writeNext(arrStr); }
            catch(Exception e){LOG.error(e);}
        }
    }
    catch (Exception sqlEx) {
        Log.e(LOG_TAG, sqlEx.getMessage(), sqlEx);
    }finally{
       if (csvWrite != null){
           csvWrite.close();
       }
    }
}