Thor
Thor

Reputation: 10058

Is there a way to simplify the try-catch block within another try-catch-finally block?

I'm new to Java and is trying to learn the concept of catching exception. I saw this code online, and it has a try-catch block within the body of another try-catch-finally block. I was just wondering if there is any way to simplify the code so it can be written in a clearer manner?

public static void main(String[] args) {
    Properties p1 = new Properties();
    OutputStream os1 = null;

    try {
        os1 = new FileOutputStream("xanadu123.properties");

        //set the properties value
        p1.setProperty("database", "localhost");
        p1.setProperty("1", "one");
        p1.setProperty("2", "two");

        p1.store(os1, "this is the comment");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (os1 != null) {
            try {
                os1.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }   
    }

Upvotes: 1

Views: 694

Answers (2)

Calvin P.
Calvin P.

Reputation: 1232

According to javadocs, in Java SE 7 and later, you can use try-with-resources and it will automatically close resources when it is finished.

public static void main(String[] args) {
    Properties p1 = new Properties();
    OutputStream os1 = null;
    try(os1 = new FileOutputStream("xanadu123.properties")){ //set the properties value
        p1.setProperty("database", "localhost");
        p1.setProperty("1", "one");
        p1.setProperty("2", "two");
        p1.store(os1, "this is the comment");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 1

Thilo
Thilo

Reputation: 262534

That is indeed a very common pattern, so a special syntax has been added to Java recently: try-with-resources

You can do

try(OutputStream os1 = new FileOutputStream("xanadu123.properties")){
}
catch (WhatYouHadBefore e){}
// no more finally, unless you want it for something else

This will be finally closed automatically (even without a finally block) and any errors during closing will be suppressed.

Upvotes: 2

Related Questions