import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.PreparedStatement;
import
java.sql.SQLException;
public
class
SQLExceptionExample {
public
static
void
main(String[] args) {
Connection connection =
null
;
PreparedStatement preparedStatement =
null
;
try
{
Class.forName(
"com.mysql.cj.jdbc.Driver"
);
String sql =
"SELECT * FROM non_existent_table"
;
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeQuery();
}
catch
(SQLException | ClassNotFoundException e) {
handleSQLException(e);
}
finally
{
try
{
if
(preparedStatement !=
null
) {
preparedStatement.close();
}
if
(connection !=
null
) {
connection.close();
}
}
catch
(SQLException e) {
handleSQLException(e);
}
}
}
private
static
void
handleSQLException(SQLException e) {
int
errorCode = e.getErrorCode();
String sqlState = e.getSQLState();
String errorMessage = e.getMessage();
System.out.println(
"SQL Error Code: "
+ errorCode);
System.out.println(
"SQL State: "
+ sqlState);
System.out.println(
"Error Message: "
+ errorMessage);
e.printStackTrace();
}
}