How to raise a custom SQLWarning?

Lennart Jorelid



The SQLWarning class extends SQLException. You may therefore treat it as any normal Exception type with respect to throwing and catching. However, the SQLException class mimics a forward traversable, linked list of Exception objects. The reason for this behavior is that a database generated SQLException rarely occurs alone - one syntactic programming error leads to a suite of SQLException objects being generated. Use the getNextException() method of the SQLException class, as seen in the class structure below:


Class structure of SQLException and SQLWarning  


Thus, to create and traverse a custom SQLWarning structure, use code similar to the one below:


Creating SQLWarning  
package se.jguru.dbTests;

// Import the SQL classes
import java.sql.*;

public abstract class RasingACustomSQLWarning
   public static void main(String[] args)
          // Simulate getting the DB data

          // All OK.
          System.out.println("Got all data.");
      catch(SQLException ex)
          // Printout root SQLException
          System.err.println("An SQL exception occurred: " + ex);

          // Get all chained SQLExceptions
          while((ex = ex.getNextException()) != null)
             System.err.println("Contained reason: " + ex);

   private static void getDataFromDB()
   throws SQLException
       // Status flag resulting from database data
       // should be created from normal business rules in
       // a live situation. 
       boolean somethingStrangeHappened = true;

           // Create two custom SQL Warnings
           SQLWarning rootWarning = 
             new SQLWarning("Business rules not properly regarded");
           SQLWarning containedWarning = 
             new SQLWarning("Product too cheap!");

           // Chain the warnings

           // Notify the caller of the warnings
           throw rootWarning;


0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact