A SQLException
object instance provides information about a database access error or other errors. Each SQLException
instance provides many types of information, including a string describing the error, which is used as the Java Exception message, available via the getMessage
method.
The sample application uses try
and catch
blocks, which are the Java mechanism for handling exceptions. With Java, if a method throws an exception, there needs to be a mechanism to handle it. Generally, a catch
block catches the exception and specifies the course of action in the event of an exception, which could simply be to display the message.
Each JDBC method throws a SQLException
if a database access error occurs. For this reason, any method in an application that executes such a method must handle the exception.
All the methods in the sample application include code for handling exceptions. For example, the getDBConnection
, which is used to get a connection to the database, throws a SQLException
, as does the getAllEmployees
method as follows:
public ResultSet getAllEmployees() throws SQLException { }
For an example of code used to catch and handle a SQLException
, refer to the code in the authenticateUser
method in the DataHandler.java
class. In this example, a try
block contains the code for the work to be done to authenticate a user, and a catch
block handles the case where the authentication fails.The following sections describe how to add code to the sample application to catch and handle a SQLException
.