Visual Studio C# Exception error message - c#

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

Related

Is there a way to return a value from a try-catch block into a preexisting variable outside of the block itself?

I feel like this may be somewhat of a dumb question, but I've tried everything I currently know to do as a beginner of C# on this. Is there any way I can return a value into one I've already set to use elsewhere? Or am I just over-complicating this whole thing? Every time I try to set the already existing variable with one inside the curly brackets I get an error. Code I used below.
static double GetAmount()
{
double amount;
try
{
Console.WriteLine("Enter in the amount for the transaction: ");
double amount1 = Convert.ToDouble(Console.ReadLine());
return amount1;
}
catch (Exception ex)
{
bool f = true;
Console.WriteLine(ex.Message);
while (f == true)
try
{
Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
double amount1 = Convert.ToDouble(Console.ReadLine());
f = false;
return amount1;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
Console.WriteLine("Please try again.");
}
}
finally
{
return amount;
}
return amount;
}
You get two compilations errors and a warning. To understand them you must know that the finally-block is always executed before returning from the try- or catch-block. I.e., return amount1; would execute the statement in finally-block return amount;. But only one return-statement can be executed. Therefore, you get the message:
CS0157 Control cannot leave the body of a finally clause
and
CS0165 Use of unassigned local variable 'amount'
because the variable is declared but is not assigned a value yet when return is called.
Also, you get the warning
CS0162 Unreachable code detected
on the last code line, because the method will either be left by one of the previous return-statements or stay in the while-loop forever. Therefore, this last return statement can never be executed.
The bool flag f is redundant. There is no point in setting it to true before the return statement since the method is exited at the return-statement. This terminates the while-loop at the same time. If you want to exit the loop without returning, you can call break;.
Simplified version using try-catch:
static double GetAmount()
{
Console.Write("Enter in the amount for the transaction: ");
while (true) {
try {
double amount = Convert.ToDouble(Console.ReadLine());
return amount;
} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.Write("Enter the total in a proper format, no letters or spaces please: ");
}
}
}
The statement while (true) introduces an endless loop. Endless unless it is left by return, break or an unhandled exception (or the frowned upon goto command).
A better alternative is to use the TryParse method that does not throw an exception
static double GetAmount()
{
Console.Write("Enter the amount for the transaction: ");
while (true) {
if (Double.TryParse(Console.ReadLine(), out double amount)) {
return amount;
}
Console.Write("Enter the total in a proper format: ");
}
}
This version has the same functionality as yours, is safe, is 3 times smaller and is much easier to read.
See also: try-finally (C# Reference)
static double GetAmount()
{
double amount = 0;
try
{
Console.WriteLine("Enter in the amount for the transaction: ");
amount = Convert.ToDouble(Console.ReadLine());
}
catch (Exception ex)
{
bool f = true;
Console.WriteLine(ex.Message);
while (f)
try
{
Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
amount = Convert.ToDouble(Console.ReadLine());
f = false;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
Console.WriteLine("Please try again.");
}
}
return amount;
}

How to handle exception in catch block?

I am trying to get the ideal way to handle exception. I googled & read that I should put try catch in the catch block as well to handle but what if any exception occurs in the nested block itself.
try
{
int a = 10;
int b = 0;
int c = a / b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
int a = 10; int b = 0;
int c = a / b;
Console.WriteLine(ex.Message.ToString());
Console.ReadKey();
}
finally
{
Console.WriteLine("Some Exception");
}
On googling I read that it should be decorated as below:
If exception occurs in Catch block itself then how to handle it in C#?
If exception occurs in Catch block itself then how to handle it in C#?
What happens if an exception occurs in Catch block in C#. Also what would be the caller result in that case
try
{
int a = 10;
int b = 0;
int c = a / b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
try
{
}
catch(Exception innerEx)
{
// What if exception here also occurs.
}
}
finally
{
Console.WriteLine("Some Exception");
}
If I do this way, then it will stuck in an infinite try-catch block.
I think there would be some better or the right way to handle this scenario.
I think there would be some better or the right way to handle this scenario.
No snark intended in this but simply, don't allow an exception to happen in the first place.
A try...catch is a language construct that ensures you handle an edge case or error you didn't mitigate and design for in the first place, hence why it's exceptional code.
In your code, you're simply throwing an error because of a division by 0, but in the real-world, you want to handle that and alert the user (or developer, or server, or whatever), and then handle the actual exceptional code, example:
static void PrintError()
{
Console.WriteLine("You must enter a valid number between {0} and {1}, excluding 0", int.MaxValue, int.MinValue);
}
static void Main(string[] args)
{
try {
int a = 10;
int b = 0;
PrintError(); // Tell user to enter valid numbers
while (b == 0) {
string user_input = Console.ReadLine();
if (int.TryParse(user_input, out b)) { // is it an actual number?
if (b == 0) { // no 0's remember user!??
PrintError();
} else {
// ok, everything checks out, so do what the system can actually handle without throwing an error
Console.WriteLine("a/b = {0}", (a / b));
}
} else {
PrintError();
}
}
} catch (Exception ex) {
Console.WriteLine("Something exceptional happened: {0}", ex);
}
}
This example could be simplified further, but it demonstrates there isn't an exception that could actually occur except something that is actually exceptional (i.e. out of memory error or some other system error).
In the event of larger code bases with multiple classes, the exception handler and finalizer would be where you could clean up resources acquired in other areas of the code, like closing a socket or file handle to ensure data is not lost.
In the event an error happens in the exception handler (something that can and does happen), you need to be aware of that and know what might happen in that case.
In the event of a C# application utilizing the .NET framework, an exception thrown within an exception will just cause the application to crash with the inner exception stack trace (versus the "outer" exception that's probably more relevant to the actual exception) if not handled.
There's plenty of "wrong" ways to handle exceptions (like not handling them at all), but there's not really a "right" way given the variable nature of exceptions.
Hope that can help.
First of all you need to know what does try,catch and finally works lets start:
Try: In this block we can write code which have the possibilities to throw some error (Better practice is to write code part in it.)
Catch: It is responsible to show error and what to do if error arises(Like in your code 10/0 throws error which can be handled in this section.)
Finally: Code written in this part will execute any how weather any error comes in or not.
Now for your query it would be better that you can use If...else in finally and code put in that part would be kept in try catch block.
For example:
bool flagCatch=false;
try
{
int a = 10;
int b = 0;
int c = a / b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
//Error handling
flagCatch=true;
Console.WriteLine(ex.Message.ToString());
Console.ReadKey();
}
finally
{
try
{
if(flagCatch)
{
//Code
}
else
{
//Code when error not comes
}
}
catch(Exception err)
{
//Error handling
}
}
I would go with the comment of Tieson T. . From my point of view it is an design issue.
I could also build an example with if statements -> if that goes wrong, I perform failure handling -> if the failure handling goes wrong, I perform failure handling, If the failure handling goes wrong ....
To make the code more readable, you can try to "hide" the try-catch blocks in method like:
static void PerformInTryCatch<T, TException>(Action<T> action, T obj) where TException : Exception
{
try
{
action(obj);
}
catch (TException exception)
{
// Perform some logging
}
}
Hope that helps.

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)
}
}

Try Catch ~ How to Display Something Different?

I have a really simple question (I'm new to c# visual studios) about the try catch method:
try
{
double seven = 7
MessageBox.Show("You Picked 7!");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I tried replacing the MessageBox.Show(ex.Message); with MessageBox.Show("Please enter a number."); but it won't work.
How should I approach this? There is the error line under the ("Please enter a number.").
Thanks in advance!
You're missing a semi-colon after declaring 'seven'
Below sample works for me.
try
{
double seven = 7;
MessageBox.Show("You Picked 7!");
}
catch(Exception ex)
{
MessageBox.Show("Please enter a number.");
}
Just a tip to if you plan on not using the exception then it's recommended you don't specify an exception as a parameter to catch. See Using catch without arguments
try
{
double seven = 7;
MessageBox.Show("You Picked 7!");
}
catch
{
MessageBox.Show("Please enter a number.");
}

Display exception message after encountering an exception

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.

Categories

Resources