views:

162

answers:

6

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?

+5  A: 

You could try catching a SQLException:

try 
{
    // Try sending a sample SQL query
} 
catch (SQLException ex) 
{
    // Print error message
}
Darin Dimitrov
A: 

You have to catch the exception:

try
{
      //Contact the server
}
catch(YourCouldNotContactServerException)
{
    //Show some friendly message
}
Oskar Kjellin
+1  A: 

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.

Streamcap
A: 

i think,solution is..

catch(Exception ex) { Responce.Write("An error occured: " + ex.Message); }

parmarupendra
A: 
 try 
{
    // Your code
} 
catch (SQLException ex) 
{
    Response.Write(ex.Message);//for web apps
Console.WriteLine(ex.Message);//for windows apps
}
Shark
A: 

you can use the same method that you use to check whether a parent class is of type subclass which is done using

 obj is NotImplementedException

where your obj is of type Exception the parent class of all exceptions.

or if you want to use the exception object later then you can use:

var niException=obj as NotImplementedException
if(niException==null)  //will be null when object is not of type NotImplementedException
return;

This logic is especially useful when you have a centralised class for handling exceptions and dont want to add multiple catch statements

Hope this helps.