Try Catch ~ How to Display Something Different? - c#

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.");
}

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

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

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.

Can't catch NullReferenceException [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
First post here, so sorry if I've got some of the niceties wrong. I'm trying to catch an exception where the user enters an invalid (non-existent) employee. I've tried many different variations, but the error is never raised. Instead the code just terminates, in this case it will drop out after the following lines:
MyPostSalary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Can anyone see what I'm doing wrong?
Complete code:
Console.Write("Employee ID: ");
myEID = Console.ReadLine();
try
{
Console.Write("Post ID: ");
myPID = Console.ReadLine();
if ((myEmployees[myEID] is MonthlyPaidEmployee) || (myEmployees[myEID] isWeeklyPaidEmployee))
{
Console.Write("Post Name: ");
MyPostName = Console.ReadLine();
Console.Write("Post Start Date: ");
MyPostStartDate = Convert.ToDateTime(Console.ReadLine());
Console.Write("Post End Date: ");
MyPostEndDate = Convert.ToDateTime(Console.ReadLine());
Console.Write("Post Salary: ");
MyPostSalary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
myPost = new Post(myPID, MyPostName, MyPostStartDate, MyPostEndDate, MyPostSalary);
if (myEmployees[myEID] is MonthlyPaidEmployee)
{
myMonthlyEmp = (MonthlyPaidEmployee)myEmployees[myEID];
myMonthlyEmp.PostHistory.Add(myPID, myPost);
}
if (myEmployees[myEID] is WeeklyPaidEmployee)
{
myWeeklyEmp = (WeeklyPaidEmployee)myEmployees[myEID];
myWeeklyEmp.WeeklyPaidEmployeePostHistory.Add(myPID, myPost);
}
}
}
catch (NullReferenceException ex)
{
Console.WriteLine("Employee ID does not exist.");
Console.WriteLine(ex.Message);
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
Are you in debug on Visual Studio (or your IDE)?
If yes, it maybe you are catching the exception but the IDE is set to show a warning message when the exception raises...
Try to run your application outside the IDE, if it works you can disable warning when NullReferenceExceptions raise , but it is quite dangerous. To do this look for "Exceptions settings" in Visual Studio (or something like this, I'm not sure because I use the italian version).
You are only catching NullReferenceException exception, but as you see in the method description of Convert.ToDouble(), it throws an InvalidCastException.
So try catch (InvalidCastException ex) instead.
Also pay attention to FormatException and OverflowException.
It's fairly clear that you are not getting a NullReferenceException. I recommend that you try the following:
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
Find out which exception you're receiving, and either catch that specific exception, or else prevent it from occurring in the first place.
You should never catch NullReferenceException.
Aren't you getting a double conversion exception? You should probably use Double.TryConvert rather than Convert.
It looks like the entered text can't be converted to a double.
Try catching an InvalidCastException.

Categories

Resources