-3

I think the following code stops if it encounters any error, period.

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);
    }
}

But I want it to:

  1. Throw an error and stop if it can't create the file to begin with.

  2. If it encounters an error on a given row, log it but move onto the next row, rather than stopping the entire thing.

Do I just move the try/catch into the loop? Does that cover it?

Pang
  • 8,605
  • 144
  • 77
  • 113
  • change `catch (Exception sqlEx) {` to do certain action on certain `Exceptions` Move the try/catch around certain code – Scary Wombat Jun 07 '17 at 01:23
  • @ScaryWombat What do you mean exactly? I am not sure what all these "certains" are – user140583 Jun 07 '17 at 01:31
  • see my answer for more help – Scary Wombat Jun 07 '17 at 01:42
  • You don't have to wrap everything into one huge try/catch block. You can always do much finer exception handling. Wrap `createNewFile` and `writeNext` into their own try/catch blocks. – tsolakp Jun 07 '17 at 01:43
  • @tsolakp So nested try/catch blocks? Outer one throwing IOException, inner one throwing Exception? – user140583 Jun 07 '17 at 01:46
  • It may not even be necessary to have a outer catc block. Usually it is not best practices to `catch` `Exception` when there is a more specific exception to catch – Scary Wombat Jun 07 '17 at 01:48
  • No, just one after another. You seldom need to nest exception handling. – tsolakp Jun 07 '17 at 01:54
  • @ScaryWombat How do I know which exceptions I have to catch individually? Why can't I just catch Exception so I don't miss anything? Otherwise I risk having it get hung up on an error depending on what happens. – user140583 Jun 07 '17 at 01:57
  • If you are using an IDE like Eclipse, then the IDE will tell you. Otherwise the java code will not compile. Looking at the Javadocs will give you the necessary information – Scary Wombat Jun 07 '17 at 01:59
  • That's one of the first things to understand anyway:don't do too many things in one method. Opening a file and processing content are two different responsibilities in the first place.... – GhostCat Jun 07 '17 at 02:01
  • @GhostCat But isn't opening a file a fairly short/quick operation? It's not considered wasteful to use two functions for a single export? – user140583 Jun 07 '17 at 02:02
  • It is about separation of concerns. When you have two methods, it is much easier to work with different catch blocks for example. And you don't worry about the overhead of calling 2 methods instead of 1 . worry about the readability of your code. – GhostCat Jun 07 '17 at 02:31
  • @GhostCat What's the correct way to separate them? Have one create the file and then pass that file object to the CSV function to make the CSVWriter / export the rows? – user140583 Jun 07 '17 at 02:32

2 Answers2

1

The Exception that you are catching is the Grandfather of all Exceptions - If you look at the javadocs you will see that the constructor new FileWriter(file) throws a IOException

So if you wanted certain action e.g. logging and quitting if this failed then try

 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
 }
Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
0

It is better if I show right in the code:

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();
       }
    }
}
tsolakp
  • 5,560
  • 1
  • 17
  • 22