Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return in a 'finally' statement

Tags:

java

file

stream

I'm trying to read ObjectOutputStream from a file and convert it to an arraylist. This whole thing is happening inside a method which should read the file and return the array list:

public static List<Building> readFromDatabase(){
    String fileName="database.txt";
    FileInputStream fileIStream=null;
    ObjectInputStream in=null;
    List<Building> buildingsArr=null;
    try
     {
        fileIStream = new FileInputStream(fileName);
        in = new ObjectInputStream(fileIStream);
        buildingsArr=(ArrayList<Building>)in.readObject();
     }
     catch(IOException e)
     {
        e.printStackTrace();
     }
     catch(ClassNotFoundException e)
     {
        Console.printPrompt("ArrayList<Building> class not found.");
        e.printStackTrace();
     }
    finally{
        Console.printPrompt("Closing file...");
        close(in);
        close(fileIStream);
        return buildingsArr;
    }
}

Java tells me that this is dangerous. What are the alternatives? I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block. I need to both make sure files will be closed, and return the array list I created as well. Any ideas?

like image 356
Jjang Avatar asked Apr 25 '26 21:04

Jjang


1 Answers

I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.

Wrong, finally block would still execute if you put return in try block. Thus you can return in your try block.

try
     {
        //your code
        return buildingsArr;
     }
     catch(IOException e)
     {
        e.printStackTrace();
     }
     catch(ClassNotFoundException e)
     {
        Console.printPrompt("ArrayList<Building> class not found.");
        e.printStackTrace();
     }
    finally{
        Console.printPrompt("Closing file...");
        close(in);
        close(fileIStream);
    }
like image 199
PermGenError Avatar answered Apr 28 '26 10:04

PermGenError