Searching Solution for this question for long period but still unmanaged to get a answer for this, I'm trying to make a search box in my application made with JAVA.
I want to catch the exception from database and telling user that column doesn't exist or duplication data, may i know how could i do this ?
SQLException is a specialized exception derived from Exception . If you catch Exception , all exception shall get caught. Even undesirable exceptions.
1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
This is not really an easy thing to do and the solution will depend a lot on the vendor of the SQL connection (ie, mySQL, oracle, etc)
I have shown one way to do this using pattern matching of the SQLException error message
private final int INEXISTENT_COLUMN_ERROR = ?
private final int DUPLICATE_DATA_ERROR = ?
private final String INEXISTENT_COLUMN_PATTERN = ?;
private final String DUPLICATE_DATA_PATTERN = ?;
...
try {
...
} catch (SQLException e){
if (e.getErrorCode() == INEXISTENT_COLUMN_ERROR)
System.out.println("User friendly error message caused by column " + this.matchPattern(e.getMessage(), this.INEXISTENT_COLUMN_PATTERN));
if (e.getErrorCode() == DUPLICATE_DATA_ERROR)
System.out.println("User friendly error message caused by duplicate data " + this.matchPattern(e.getMessage(), this.DUPLICATE_DATA_PATTERN));
}
...
private String matchPattern(final String string, final String pattern) {
final Pattern p = Pattern.compile(pattern);
final Matcher m = p.matcher(string);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With