A
A
Andrey Lubchuk2016-01-13 15:21:24
Java
Andrey Lubchuk, 2016-01-13 15:21:24

Return in a try/catch block?

How can I return String[] items if it's only visible in the try/catch block? And the line return items gives an error that it is not initialized.
Example:

public String ComboBX() {
        try {
            String query = "SELECT id, name, price FROM menu";
            Connection connection = null;
            connection = DriverManager.getConnection(ConnectToDatabase.URL, ConnectToDatabase.USERNAME, ConnectToDatabase.PASSWORD);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
            Driver driver = new FabricMySQLDriver();
            DriverManager.registerDriver(driver);

            String[] items = {"1", "2", "3"};
         
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return items;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FoxInSox, 2016-01-13
@AngelX96

Declare the items variable before the try block

String[] items = null;
try{
//...
return items;

C
Copperfield, 2016-01-13
@Copperfield

Move it outside the try-catch block:
String[] items = null;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question