0

I cannot seem to be able to declare the following as an instance variable.

   public Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

If declared inside a method/test method then it works fine.

"Default constructor cannot handle exception type SQLException thrown by implicit super constructor. Must define an explicit constructor" is the error thrown, I've also tried declaring it in another class and retrieving it from there.

Any help appreciated.

2
  • Define an explicit constructor? Commented Jan 4, 2018 at 11:22
  • 1
    Option 1: Use a constructor. Option 2: Use an initialization block. Commented Jan 4, 2018 at 11:25

1 Answer 1

2

It's not the declaration that's failing - it's the attempt to initialize the variable using an expression which can throw a checked exception.

You should declare the field, then initialize it in a constructor. That constructor will have to declare that it throws SQLException (or catch the exception itself).

As a side note, I'd strongly suggest avoiding public fields.

For example:

public class Foo {
    private final Statement statement;

    public Foo(Connection connection) throws SQLException {
        statement = connection.createStatement(...);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This has fixed my issue! I'm still learning a lot about Java so I'll definitely try do some research into structuring etc. in Java to improve my code :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.