Is it wise to throw exceptions in a constructor?

architecture, java, jdbc

Solution

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:

- How often should Connection, Statement and ResultSet be closed in JDBC?

- JDBC MySql connection pooling practices to avoid exhausted connection pool

- When my app loses connection, how should I recover it?

Problem

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?

Original source

Related problems