I want to check if the server is not accessible and if its not accessible i want to print a friendly message on my login page. Like when user input its credential and in exception i got
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
this exception. So how should i when which exception is occurred so i can display a message?
Try to put the most unusual exceptions at the top, working your way down the list towards more common ones. The catch sequence is sequential - if you put catch(Exception) at the top, it will always catch on that line no matter what exceptions you code for beneath it. Show activity on this post.
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System. Exception is the base class for all exceptions in C#.
I know this is an older post, but if you are going to handle all exceptions the same way and/or are using the information for error reports or something similar (instead of notifying the user of the specifics) you can use the following.
try
{
//do something here
}
catch(Exception ex)
{
MessageBox.Show(ex.GetType().ToString()); //will print System.NullReferenceException for example
}
You need to know at code-time what exceptions to expect, in order to catch them accordingly. As Dimitrov stated, a SQLException is thrown when the connection to an SQL server fails, so catching that specifically is a good tactic.
You want to catch the various exceptions in order, like so:
try
{
//some code
}
catch(TypeOfException exOne)
{
//handle TypeOfException someway
}
catch (OtherTypeOfException exTwo)
{
//handle OtherTypeOfException some other way
}
catch (Exception ex)
{
//handle unknown exceptions in a general way
}
finally
{
//any required cleanup code goes here
}
Try to put the most unusual exceptions at the top, working your way down the list towards more common ones. The catch sequence is sequential - if you put catch(Exception) at the top, it will always catch on that line no matter what exceptions you code for beneath it.
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