Should we ignore an IOException when the Buffered stream is closed?

I load the xml content and save it to disk. Then I read it and try to make out. When I successfully parsed the xml, should I ignore the IOException in 7 lines?

 catch (IOException ignore) {}

Or may some problems arise?

private HashMap <String, VideoDto> loadContent(String url){
    try {
        BufferedInputStream bStream = httpGateway.loadContents();
        cachedContent = xmlParser.parseVideos(bStream);
        try {
            bStream.close();
        } catch (IOException ignore) {}
        return cachedContent;
    } catch (XMLStreamException e) {
        throw new IllegalStateException("I/O error during integration", e);
    }
}


public BufferedInputStream loadContents() {
    URL source = config.getContentPath();
    URL target= config.getLastImportedFile();
    try {
        ReadableByteChannel rbc = Channels.newChannel(source.openStream());
        FileOutputStream fos = new FileOutputStream(target.getFile());
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Wrong url format", e);
    } catch (IOException e) {
        throw new IllegalArgumentException("I/O error while saving "+target, e);
    }

   return createBufferStream(config.getLastImportedFile());
}

private BufferedInputStream createBufferStream(URL url){
    try {
        return new BufferedInputStream(url.openConnection().getInputStream());
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
+4
source share
5 answers

There are three parts to this question:

Q1: Should a squash exception be ignored?

I think the answer is ... "it depends."

If the reason for the exception is known, and you can catch it precisely (i.e., not catch the exceptions with different reasons), and the right thing to do is to ignore it then ... IMO ... Yes, that’s acceptable.

Otherwise. No.

Q2: IOException , ?

, . IOException , , . , , . , , -, , .

Q3: IOException?

, . :

    } catch (IOException ex) {
        // possibly log the exception here.
        throw new AssertionError("Unexpected exception", ex);
    }

, - , , / , .

, , IOException , ( ) .

+2

, . .

, - , , .

e.printStackTrace();

, .

0

try, Java 7:

try (BufferedInputStream bStream = httpGateway.loadContents();) {
    cachedContent = xmlParser.parseVideos(bStream);
}

.close().

, try.

0

, () , , . , , , .

try-with-resources, :

try (BufferedInputStream bStream = httpGateway.loadContents()) {
    cachedContent = xmlParser.parseVideos(bStream);
}
0

Effective Java Joshua Bloch , , , . , , , .

0

Source: https://habr.com/ru/post/1584438/


All Articles