Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Dear Developers,
This is my basic try and catch block
try
{
some code..
}
catch(exception ex)
{
label1.text=ex.Message;
}


it works fine and display the respective exceptions, But as per my requirement
for Example-- "Violation of UNIQUE KEY constraint 'unique_User'. Cannot insert duplicate key in object 'dbo.UserDetails'. The statement has been terminated"
then i want to print my own message as"user name already exists"
How to obtain this..
Any answers ll be appreciated...
Thanku
Posted
Updated 21-Mar-12 3:33am
v2

read this articale

i hope you will get full information about try catch

Using Try... Catch..., Finally![^]
 
Share this answer
 
v2
Create Custom Exceptions as per your requirements.

Check below links on how to create custom exceptions.
First[^]

Second[^]

Third[^]
 
Share this answer
 
v2
Comments
The Doer 21-Mar-12 7:57am    
even i can use like this,
catch (SqlException ex )
But Sql Exception can itself contain many more exceptions, so how to address any specified one there..??
nagendrathecoder 21-Mar-12 8:40am    
I would say why wait for the exceptions.....handle validations.
u can have more than one Exception like one for IO another for SQL and so on .

C#
try
{
some code..
}
catch(exception ex)
{
   label1.text=ex.Message;
}
catch(exception ex)
{
   label1.text=ex.Message;
}
catch(exception ex)
{
   label1.text=ex.Message;
}
catch(exception ex)
{
   label1.text=ex.Message;
}
 
Share this answer
 
Hi,

Insert between the try and the catch a new catch block for a DivideByZeroException.

try
{
some code..
}
catch(DivideByZeroException)
{
   Label1.Text = "You devided by zero";
}
catch(Exception ex)
{
   label1.text=ex.Message;
}


Piet
 
Share this answer
 
Comments
The Doer 21-Mar-12 7:59am    
my exception is---
Violation of UNIQUE KEY constraint 'unique_User'. Cannot insert duplicate key in object 'dbo.UserDetails'. The statement has been terminated

how can i address this ?? if i want to print the message as 'User already exists"
just use catch{} and print your own message,...
 
Share this answer
 
Comments
nagendrathecoder 21-Mar-12 7:46am    
This way same message will be displayed for all exceptions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900