Home » Java Basics » try/catch/finally » try/catch/finally InputStream example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

try/catch/finally InputStream example

This is an example of an InputStream in a try/catch/finally statement. Using try/catch/finally statement to create an InputStream implies that you should:

  • Create an InputStream and initialize it to null.
  • Open a try statement and initialize the InputStream to a FileInputStream, by opening a connection to an actual file.
  • Include the catch statement to catch any IOExceptions thrown while trying to open the connection to the file.
  • Include the finally statement. Code included here will be executed always. So here the InputStream is closed. A try/catch statement can be included here too, to catch any IOExceptions thrown while trying to close the InputStream.

Let’s take a look at the code snippet that follows:

InputStream in = null;

    in = new FileInputStream(new File("test.txt"));
    //do stuff with in
catch(IOException ie)

    catch(IOException ioe)

  //can't do anything about it

Related Article:

Reference: Garbage collection with Automatic Resource Management in Java 7 from our JCG partner Swaranga at the The Java HotSpot blog
This was an example of an InputStream in a try/catch/finally statement in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

Notify of