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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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

I have read and agree to the terms & conditions

 

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