Display exception message after encountering an exception - c#

I have a program that reads the amount entered
If the user enters a non numeric input,
try {
number = Convert.ToDouble(input);
}
catch (Exception ex) {
Response.Redirect(Request.RawUrl);
Label1.Text = ex.Message;
}
But the exception message doesn't show when the page is refreshed. IS there a better way to do this?
Thanks.

Related

Visual Studio C# Exception error message

Here is my code. when the user clicks the "calculate" button, the code will execute it. However, if the user doesn't put any number, the exception throws and the error message will pop up. I wan't my error message says that "You forgot to put the number!" but the automatic message that says "Input string was not in a correct format" pops up. How to change the error message?
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
// Local variables
String num1;
String num2;
double number1;
double number2;
double result;
// Get the numbers from the textboxes
num1 = txtInput1.Text;
num2 = txtInput2.Text;
number1 = double.Parse(num1);
number2 = double.Parse(num2);
// Determine the user clicks the Addition radiobutton
if (rdbAdd.Checked)
{
// Add two numbers
result = number1 + number2;
}
else
{
// Determine the user clicks the Subtraction radiobutton
if (rdbSubtract.Checked)
{
// Subtract numbers
result = number1 - number2;
}
else
{
// Determine the user clicks the Multiply radiobutton
if (rdbMultiply.Checked)
{
// Multiply numbers
result = number1 * number2;
}
else
{
// Devide numbers when the user clicks the Devision radiobutton
result = number1 / number2;
}
}
}
// Display the result
txtDisplay.Text = result.ToString();
}
catch (Exception ex)
{
// Display an error message
MessageBox.Show(ex.Message);
}
}
To display your choice of messages...
MessageBox.Show("Your message goes here.")
The exception has it's own message, you should intercept the type of exception you are interested in and display your message approriate to the exception. If there is nothing in the text fields, then Double.Parse throws the exception (look at Double.Parse for the Exceptions it throws)
But if number2 is zero, and the user chooses to "divide", you will get a different exception (divide by zero).
Generally, you should validate your input, and simply using Double.Parse might be all you need. But typically, you need more. Also, if you intend to internationalize your application, you need to parse according to locale. See the link above, there is a method for localized parsing.
This is the default message of this exception which is a FormatException.
You can catch that kind of exceptions and then just display your own message:
try
{
.... your code ...
}
catch (FormatException ex)
{
//FormatException was thrown, display your message
MessageBox.Show("You forgot to put the number!");
}
catch (Exception ex)
{
// Some other kind of exception was thrown ...
MessageBox.Show(ex.Message);
}
You can have several "catch" clauses, one for each type of exception that you want to handle:
try
{
// Your code goes here
}
catch (DivideByZeroException ex)
{
MessageBox.Show("Cannot divide by zero! " + ex.Message);
}
catch (Exception ex)
{
// This is a generic exception
MessageBox.Show("Error: " + ex.Message);
}
You must order them from more specific to more generic.
may be you try this one, you cannot proceed if one of the txtInput1 and txtInput2 are null or Empty.
if(string.IsNullOrWhiteSpace(txtInput1.Text) == true)
{
MessageBox.Show("Your message goes here.");
return; // this is important, return if true
}
if(string.IsNullOrWhiteSpace(txtInput2.Text) == true)
{
MessageBox.Show("Your message goes here.");
return; // this is important, return if true
}
// then
. . . . . // proceed if no problem found

Looping in Handling Exception

I have made a simple program. I want to add loop for try, catch statement, so if the user write input, he gets and error message and the program let him to write again.
Console.WriteLine("Enter The File Location");
string userValue = Console.ReadLine();
try
{
string content = File.ReadAllText(userValue);
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine(ex.Message);
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine("Could not find the Directory");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
You can wrap your code inside a while loop, that repeats the code until a successful operation has been completed.
var success = false;
while (success == false)
{
Console.WriteLine("Enter The File Location");
string userValue = Console.ReadLine();
try
{
string content = File.ReadAllText(userValue);
Console.WriteLine(content);
success = true;
}
catch (FileNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine(ex.Message);
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("There was a Problem");
Console.WriteLine("Could not find the Directory");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
When you are able to check for invalid input, it's usually best to do that rather than let an exception happen.
In your case you can check File.Exists(...) and/or Directory.Exists(...) based on the user's input.
You could make those the conditions of your loop statement, so continue to prompt the user until they use a correct directory and file.
However, I would suggest that this is not necessarily the best user experience, as you are expecting them to know a valid file and directory, which they may not. Certainly you should provide a way for them to exit out of the loop.
I would use a while construct with a specified condition when the user input is done (when you detect an Enter keypress, or have a complete command or otherwise).
Then you can loop while that condition is not met (and there is no unrecoverable error), and use your code above to check for user errors and print messages when needed.
You don't need loop. Yuo can use Recursive function.
Try this: https://dotnetfiddle.net/4NR26P

How to notify an exception in C#?

I have an exception occurred when the Database connection failed in a Class. The problem is how do I notify my Main Window that this exception is caught and show a message box to notify my user?
Thanks
Use the Try ... Catch clause like this:
try
{
// The code that could generate an exception
}
catch(Exception ex)
{
MessageBox.Show("Error: " ex.Message);
}
Or if you're using SQL-Server connection, use it like this:
try
{
// The code that could generate an exception
}
catch(SqlException ex)
{
MessageBox.Show("SQL Error: " ex.Message);
}
Thanks. I may have not make my question clearly. I mean this exception
is occurred in one class, but the message box should be show in an
other windows class. So how do I communicate and show this error?
From your clarification in one of the comments:
So if you have class TestClass.cs with method Test in it.
public void Test()
{
//if you want to throw an exception defined by your business logic
if(someCondition == false)
throw CustomException();
//if you have exception in the code
int a = 5;
int b =0;
//here you will be thrown an exception can't divide by 0.
int c = a/b;
}
Your winform Button Click or whatever
public void Button_Click1(object sender, EventArgs e)
{
try
{
TestClass cl = new TestClass();
cl.Test();
}
catch(CustomException custEx)
{
//this for your Bussines logic exception
//write your message
}
catch(DivideByZeroException div)
{
//this for divide by zero exception
//write message
}
//you can catch all other exception like this but I don't advice you to do that
catch(Exception ex)
{
//for this to working properly, this catch should be under all of others(last priority)
}
}

Is multiple try-catch in error sensitive code considered a good practice?

I have a code segment that is responsible for orchestrating the execution of a few modules and it is very sensitive to errors - I want to make sure I log and alert about every exception that occurs.
Right now I have something like this:
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
}
catch (Exception ex)
{
string errorMessage = string.Format("Module A failed doing it's thing. Specific exception: {0}", ex.Message);
// Log exception, send alerts, etc.
}
try
{
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
string errorMessage = string.Format("Module B failed doing it's thing. Specific exception: {0}", ex.Message);
// Log exception, send alerts, etc.
}
// etc for other modules.
It looks to me that the multiple try-catch is making this segment less readable. Is it indeed the right thing to do?
Yes, it's the right thing.
But you should have the performance in in mind, maybe it's better to put all method calls in one try/catch and add stack trace and error information in the exception in the methiod itself.
public void ModuleA.DoSomethingA()
{
throw new Exception("Error in module A");
}
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
// get information about exception in the error message
}
You did well.
This way, you can process the error after each module. If you want to run it all and then do error handling, consider this alternative:
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch(ModuleAException ex)
{
// handle specific error
}
catch(ModuleBException ex)
{
// handle other specific error
}
catch (Exception ex)
{
// handle all other errors, do logging, etc.
}
i think that depends on the approach that you want to follow.
It seems like you error messsages are different for each module that raises exception so i guess the approach that you followed is right.
you could have put the whole thing in a big try - catch block then in that case you will not know which module caused the exception as a generic excpetion gets printed.
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
string errorMessage = string.Format("Either Module A or B failed", ex.Message);
// Log exception, send alerts, etc.
}
So if you want your exception handling to not be cleaner use the above code.
Otherwise what you followed is absolutely fine.

C# saving an image from PictureBox

i have a code like this:
private void Load_Button_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog()==DialogResult.OK){
MessageBox.Show(dialog.FileName,"My Application", MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
string s;
s=".bmp";
if (dialog.FileName.Substring(dialog.FileName.LastIndexOf('.')).Equals(s))
{
picBox_1.Load(dialog.FileName);
BitmapFile = new Bitmap(dialog.FileName.ToString());
}
else {
MessageBox.Show("Not a BMP file!");
}
}
}
so, load image. and have an error in this:
private void Save_Button_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
try
{
if (picBox_1.Image != null)
{
if (dialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(dialog.FileName, "My Application", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
string s;
s = ".bmp";
if (dialog.FileName.Substring(dialog.FileName.LastIndexOf('.')).Equals(s))
{
picBox_1.Image.Save(dialog.FileName.ToString());
//BitmapFile.Dispose();
}
else
{
MessageBox.Show("Not a BMP file!");
}
}
}
else
{
MessageBox.Show("My PicBox is empty!");
}
}
catch (Exception) { MessageBox.Show("Cannot save file, error!"); }
}
this is general GDI error. I suppose, that i can't write to file (not enough rights, maybe). how can i improve this error?
you should catch the exceptions properly, not with a MessageBox which tells you nothing about the exact exception thrown!
at minimum your catch block should look like this:
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
and I say at minimum because you should in fact log the exception somewhere, using a logging framework like NLog or Log4Net and dump stack trace and other details. You are not even able to tell the excact type of Exception if you show a message with a static string and not the details of the actual exception.
You should only catch specific exceptions that you intend to handle or recover from, and log the details. Never catch Exception as you would potentially be masking bigger issues with your server if they occur.
Unexpected exceptions should bubble up so that the cause can quickly be identified when they occur.
See here for Best Practices for Handling Exceptions.
You're eating the exception and losing all the juicy detail. Try changing your catch block to something like this to see what's going on:
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "Error Saving Image", MessageBoxIcons.Error);
}
Also, consider implementing some logging (to the event viewer and/or text file. This will allow you to have a simple message box, but with all the juicy detail put somewhere useful to fetch after the event.
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error Saving Image", MessageBoxIcon.Error);
// _logger is a private field on this class in this case.
_logger.Log(ex, string.Format("Saving image to {0}", dialog.Filename))
}
You could look at Log4net amongst other things for the actual logging, but at the very least write a class to write exception detail to the event viewer.

Categories

Resources