try/catch/finally

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;

try
{
    in = new FileInputStream(new File("test.txt"));
    //do stuff with in
}
catch(IOException ie)
{
    //SOPs
}
finally
{
    try
    {

  in.close();
    }
    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.

Ilias Tsagklis

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button