ArthurMFB
ArthurMFB

Reputation: 65

Customize exception messages from try-catch

I'm currently into something that I know it is possible, but not sure how to do it.

I want to display an customized error message in a program that people can insert data, delete, update, search and other things like that. Sadly, I can't just show the message like it here:

try { }
catch (Exception ex)
{ 
    MessageBox.Show(ex.Message);
}

All I need is a number that describes the exception. So, if I know the specific number, I can associate with the message I want. I tried the following code, but I don't know how to associate the exception I get (is there any library or something?).

I'm doing that because the users won't speak English at all.

I have seen some cases in which people who knows the exception (like divide by zero) can customize it. But, As I will have different messages, I should do it another way.

try
{
   catch (Exception ex)
   {
        MessageBox.Show(ex.HResult.ToString()); //Here I cant get a number, and, 
   }      //in one case, I get the result 2147467259 which should be about 
}         //inserting a data too long in a MySQL table

Upvotes: 1

Views: 1052

Answers (1)

Jamshaid K.
Jamshaid K.

Reputation: 4547

Bro, I will Suggest you to first analyze the cause of the exception and then write a custom message, Another Rough thing you can do is check the message of exception and perform something like this in with Exception object

if(ex.Message.Contains("PRIMARY_KEY"))
{
   MessageBox.Show("Primary Key Violation, You Cannot Add Duplicate Records!");
}

Upvotes: 2

Related Questions