I want to handle different problems, while doing database operations, differently.
e.g. The operation may fail because of wrong database credentials or due to network problem. Or it may fail because the query is not correct (if string value is being passed in the int type column)
In my C# code, we only have SqlException
which has collection of SqlErrors
. However there are many severity levels.
How can i easily identify the cause of the SqlException ? How can i determine the exception is because of the connectivity problem or authentication failure or because of the problem with the query.
I am using SQL Server 2005.
Try: Program statements that can raise the exception should be kept within a try block. Catch: If any exception occurs in the try block, it will be thrown. We can catch that exception using the Catch block and handle it in the code. Throw: System-generated exceptions are automatically thrown by JVM.
A cause. A SQLException instance might have a causal relationship, which consists of one or more Throwable objects that caused the SQLException instance to be thrown. To navigate this chain of causes, recursively call the method SQLException. getCause until a null value is returned.
An exception that provides information on a database access error or other errors. Each SQLException provides several kinds of information: a string describing the error. This is used as the Java Exception message, available via the method getMesasge .
If you must have your own message, you can create your own exception class, then assign the SqlException to the InnerException property. Or throw one of the other exceptions and do the same thing (the assign part).
Try something like this, this will help you in handling different conditions.
use a try catch block like this:
try
{
...
...
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 4060: // Invalid Database
....
break;
case 18456: // Login Failed
....
break;
case 547: // ForeignKey Violation
....
break;
case 2627:
// Unique Index/ Primary key Violation/ Constriant Violation
....
break;
case 2601: // Unique Index/Constriant Violation
....
break;
default:
....
break;
}
}
SQLException
exposes the property Class
which should give you the severity level.
More information here.
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