LoslegenKostenlos loslegen

Handling Database Exceptions

Database operations can fail for several reasons: a table may not exist, a column name may be misspelled, or the connection may drop. JDBC uses SQLException to capture these errors, providing details like error messages and SQL state codes.

The query in this exercise has an intentional typo (boks instead of books).

Diese Übung ist Teil des Kurses

Querying a PostgreSQL Database in Java

Kurs anzeigen

Anleitung zur Übung

  • Catch the exception when the query fails.
  • Print the error message and SQLState from the exception.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

public class Main {
    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(Credentials.URL, Credentials.USER, Credentials.PASSWORD);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM boks")) {
            while (rs.next()) {
                System.out.println(rs.getString("title"));
                System.out.println(rs.getInt("publication_year"));
            }
        // Catch database exceptions
        } catch (____ e) {
            // Print the error message and SQLState
            System.out.println("Error: " + e.____());
            System.out.println("SQLState: " + e.____());
        }
    }
}
Code bearbeiten und ausführen