Returning variable from inside try/catch block

Good evening guys. Look, I've got this big trouble and see no solution for it, but I know there must be a way to solve this...

public static int[] prices() throws Exception {
    try {
        Connection con = getConnection();
        Statement search = con.createStatement();
        ResultSet rs = search.executeQuery("SELECT nomeProd FROM main;");
        rs.last();
        int k = rs.getRow();
        rs.beforeFirst();
        int prices[] = new int[k];

        /*
        for( int i = 1; i <= k; i++ ) {

        }
        */

        return prices;
    } catch(Exception e) {
        System.out.println(e);
    }
}

So, what I need is to return the prices array from inside the try-catch block or I won't be able to get the variable "k". If I initialize k as 0 before the try block, and create the array after the catch block, then I won't be able to access the ResultSet variable (well, yes, I could connect, create a statement and resultset all over again but that would probably just cause me more headache).

Can anyone help me on this? Thanks!

Upvotes: 1

Views: 1262

Answers (1)

Juned Ahsan
Juned Ahsan

Reputation: 68715

Just declare your variables outside try/catch block, then they will be accessible both inside and outside the block. For example:

Connection con = null;
try {
         con = getConnection();
       // rest of code on the same lines

}

Upvotes: 4

Related Questions