0

There is a method that finds indices of subString occurrences in inStream (actually it's a file)

public static ArrayList<Long> searchSubStrings(InputStream inStream, String subString) throws IOException {

        ArrayList<Long> indexes = new ArrayList<>();
        String subStringName = new String(subString.getBytes(),StandardCharsets.UTF_8);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8))) { // one more battle
            int ch;                     //
            long headSubstring = 0;      // write here position in file of substring's beginning
            long currPosInFile = 0;      // we go through the file char by char
            int currPosInSubstring = 0; //
            boolean isSubString = false;

            while ((ch = reader.read()) != -1) {
                /*cool algo*/
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return indexes;
}

What are the pros and cons of handling the exception here?

also I use reader.reset(); in /cool algo/ and I'm not sure that BufferedReader won't start reading from file after reset call.

  • 2
    Well, you'll have to decide what to return if an exception occurs - a partial list? an empty list? Another option: you could also throw a custom exception that indicates that the operation failed, providing only the information the caller needs to know. As failure to read from an input usually needs to be handled differently from an empty result, the caller will need to know about it. – Hulk Dec 18 '20 at 07:12
  • 1
    As a general rule, you should only handle exceptions if you actually know what to do in case they occur - this will probably not be the case here. Any exceptions will probably be due to the state of the given input stream, and this method cannot do anything about that - only the caller may be able to. – Hulk Dec 18 '20 at 07:20

0 Answers0