2

I am building DB class, in the constructor I want to establish the connection with database, so that static dbLink is accessible by the rest of the functions inside that class. Is that a good approach?

lunar
  • 1,172
  • 7
  • 18
  • 29

4 Answers4

12

As to the concrete question, surely it's legal to throw exceptions in a constructor. There's no other sane way to prevent the "DB class" instance from being used with a broken connection.

As to the concrete functional requirement, you've another major problem. You should not be creating a DB connection in the constructor of a "DB class" and surely not make it static. This indicates that you're intending to keep the connection open as long as the instance of the "DB class" lives in Java's memory. This is in turn a very bad idea. The connection should instead be created in the very same try block as where you're executing the SQL query/queries. The connection should also be closed in the finally block of that try block. This prevents resource leaking in long term which would otherwise cause your application to crash because the DB server times out the resource because it's been open for too long, or runs out of resources because too many connections have been opened.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

My suggestion would be to provide a connect() method in your class that will throw exceptions and let your class instantiate without exceptions.

anubhava
  • 761,203
  • 64
  • 569
  • 643
2

"Hello, yes, it is normal to throw an exception from a constructor. In fact, throwing an exception is the only way that a constructor can fail.

However, you should be cautious about throwing any exception from a constructor that is a subclass of RuntimeException. The Java compiler does not force the calling code to handle such exceptions, and therefore they impose some additional risk. It is okay to use them sometimes, but be careful."

From here: http://en.allexperts.com/q/Java-1046/normal-throw-exception-constructor.htm

dexametason
  • 1,133
  • 7
  • 16
1

Typically, creating a connection object of some sort does not actually establish a connection, it just sets up the connection to be made. It makes more sense to have a connect() method which establishes the connection or throws an exception if it cannot.

I don't think it makes sense to have the constructor establish a connection, so it shouldn't throw any exceptions.

Tyler Treat
  • 14,640
  • 15
  • 80
  • 115