1

I'm confused about try/catch with a throws. I have two possible IOExceptions within a function. One, I want to catch and continue. The other I want to throw an exception for the previous function to deal with.

I'd like to catch an IOException if it cannot open a file, notify the user, and continue. If an IOException appears when the directory is cleared, I want to throw an exception and handle it in the calling code.

Will it throw the exception that clearUploads() may throw while catching the exception if it can't open the file?

In main:

 output = parseCSV(fileList); 

Functions:

private static String parseCSV(List<File> fileList) throws IOException { String returnString = ""; String[] tokens = null; String currFileName = ""; for(File file: fileList){ currFileName = file.getName(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { } //do stuff } br.close(); } catch (FileNotFoundException e) { returnString += "Cannot find " + currfileName + "!\n"; } catch (IOException e) { returnString += "Cannot open " + currFileName + "!\n"; } } clearUploads(); if (returnString.equals("")) { returnString = "Files uploaded and saved successfully"; } return returnString; } private static void clearUploads() throws IOException { FileUtils.cleanDirectory(new File(filePath)); } 
4
  • 4
    Will it throw the exception that clearUploads() may throw while catching the exception if it can't open the file? Yes. Next question. Commented Apr 5, 2018 at 14:34
  • @ElliottFrisch do you actually see a try catch block around clearUploads()? No it won't, it's not within scope of the block implemented. Next incompetent comment. Commented Apr 5, 2018 at 14:42
  • @apexlol Huh? It definitely throws the same exception from clearUploads (since it doesn't handle the exception). I said nothing about a try catch block. clearUploads isn't in a try-catch block. Commented Apr 5, 2018 at 15:05
  • 1
    Also your br.close() isn't safe. You should call it in finally or, better use try-with-resources. Commented Apr 5, 2018 at 15:40

1 Answer 1

2

The try block will catch anything that it's inside it's scope and that is compatible with the types in the catch part, since clearUploads is outside the try block it will not be caught by that block in particular.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. A dumb question, I know, but I'd rather be sure than remain confused.
Try looking at the documentation before asking a question in SO, most of the time it might take a bit longer but you will learn much more. try,scope

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.