How do I run this code without using try catch? - c#

WriteLine("Before parsing");
Write("What is your age? ");
string? input = ReadLine(); // or use "49" in a notebook
try
{
int age = int.Parse(input!);
WriteLine($"You are {age} years old.");
}
catch (OverflowException)
{
WriteLine("Your age is a valid number format but it is either too big or small.");
}
catch (FormatException)
{
WriteLine("The age you entered is not a valid number format.");
}
catch (Exception ex)
{
WriteLine($"{ex.GetType()} says {ex.Message}");
}
WriteLine("After parsing");
Write("Enter an amount: ");
string amount = ReadLine()!;
if (string.IsNullOrEmpty(amount)) return;
try
{
decimal amountValue = decimal.Parse(amount);
WriteLine($"Amount formatted as currency: {amountValue:C}");
}
catch (FormatException) when (amount.Contains("$"))
{
WriteLine("Amounts cannot use the dollar sign!");
}
catch (FormatException)
{
WriteLine("Amounts must only contain digits!");
}
I'm supposed to update or replace the try catch clauses with the TryParse() method but there's multiple catch statements within the try catch statements. The result of the c# code is not supposed to have any try catch clauses but still performs handling exceptions.

The try-catch block in the code is used to handle exceptions that may occur when parsing a string to an integer or decimal.
To run the code without using try-catch, you can use the built-in method int.TryParse or decimal.TryParse, which returns a boolean indicating if the parsing was successful or not, rather than throwing an exception.
Here's an example:
WriteLine("Before parsing");
Write("What is your age? ");
string? input = ReadLine(); // or use "49" in a notebook
if (int.TryParse(input!, out int age))
{
WriteLine($"You are {age} years old.");
}
else
{
WriteLine("The age you entered is not a valid number format.");
}
WriteLine("After parsing");
Write("Enter an amount: ");
string amount = ReadLine()!;
if (string.IsNullOrEmpty(amount)) return;
if (decimal.TryParse(amount, out decimal amountValue))
{
WriteLine($"Amount formatted as currency: {amountValue:C}");
}
else if (amount.Contains("$"))
{
WriteLine("Amounts cannot use the dollar sign!");
}
else
{
WriteLine("Amounts must only contain digits!");
}

Related

Infinite Loop C# Fix Please

Console.WriteLine("Mortgage Loan Calculator");
Console.WriteLine("------------------------------------");
C1 c1 = new C1();
while (true)
{
bool continueLoop = true;
do
{
try
{
Console.WriteLine("Enter loan amount: ");
loanAmount = Convert.ToDouble(Console.ReadLine());
checkLoanAmount(loanAmount);
continueLoop = false;
}
catch (FormatException formatException)
{
Console.WriteLine("\n" + formatException.Message);
Console.WriteLine("Please enter a double value. \n");
continueLoop = true;
}
catch (MyRangeException negativeNumberException)
{
Console.WriteLine("\n" + negativeNumberException.test);
}
catch (Exception exception)
{
Console.WriteLine("\n" + exception.Message);
Console.WriteLine("Input string was not in a correct format");
continueLoop = true;
}
} while (continueLoop);
do
{
try
{
Console.WriteLine("Enter loan amount: ");
years = Convert.ToDouble(Console.ReadLine());
checkLoanYears(years);
}
catch (FormatException formatException)
{
Console.WriteLine("\n" + formatException.Message);
Console.WriteLine("Please enter a double value. \n");
}
catch (MyRangeException negativeNumberException)
{
Console.WriteLine("\n" + negativeNumberException.Message);
}
catch (Exception exception)
{
Console.WriteLine("\n" + exception.Message);
Console.WriteLine("Input string was not in a correct format");
}
} while (continueLoop);
do
{
try
{
Console.WriteLine("Enter loan amount: ");
interest = Convert.ToDouble(Console.ReadLine());
checkLoanInterest(interest);
}
catch (FormatException formatException)
{
Console.WriteLine("\n" + formatException.Message);
Console.WriteLine("Please enter a double value. \n");
}
catch (MyRangeException negativeNumberException)
{
Console.WriteLine("\n" + negativeNumberException.Message);
}
catch (Exception exception)
{
Console.WriteLine("\n" + exception.Message);
Console.WriteLine("Input string was not in a correct format");
}
} while (continueLoop);
}
So I'm trying to create a Loan Program with exception handling. I have the code working to where it takes the exceptions when I input in the wrong format. The problem that I'm having though is that it keeps it in an infinite loop asking for the loan amount instead of going to the next question. If anyone could give me some advice of what I'm doing wrong that would be greatly appreciated!
Here is a partial list of things I see with your code:
Class C1 does nothing and it is not used
Outer while loop has no exit condition while(true) { } and no break; statement inside.
Repeating (copy/paste) code for similar functionality to receive user inputs. Major clue when you see this pull the code in a function, and use a loop if necessary to call the function. Here I think you use need to manualy call the function three times.
Using try{} catch{} as part of regular code instead of only for something actually un-expected. This is the reason C# has the int.TryParse(), float.TryParse() and decimal.TryParse() method, in order to branch your code depending if the input is valid or not
if(float.TryParse(input, out var value))
{
// use float `value`
} else {
// invalid input
}
Exceptions are for, well, exceptional events. Nothing in a user input program like this should be exceptional.
Your code for the loanAmount seems to be right though. It's setting continueLoop = false; and that should allow the loop to exit. You haven't shown us checkLoanAmount (which should be named CheckLoanAmount) so I can't tell you if that's causing your problem.
In any case, here's how I would do this kind of app:
Console.WriteLine("Mortgage Loan Calculator");
Console.WriteLine("------------------------------------");
decimal ReadDecimal(string message, Func<decimal, bool> validator, string validation)
{
while (true)
{
Console.WriteLine(message);
if (decimal.TryParse(Console.ReadLine(), out decimal result) && validator(result))
{
return result;
}
Console.WriteLine();
Console.WriteLine(validation);
Console.WriteLine();
}
}
decimal loanAmount = ReadDecimal("Enter loan amount: ", d => d > 0m, "Amount must be greater than zero.");
decimal years = ReadDecimal("Enter number of years: ", d => d > 0m, "Amount must be greater than zero.");
decimal interest = ReadDecimal("Enter interest rate: ", d => d >= 0m && d <= 100, "Amount must be between zero and 100.");

Constraining user input to one of a specified set of values

(I have tried finding a similar problem with no luck, so I am hoping maybe someone can provide a solution)
I have a do while loop in my first class with the goal of looping until the user inputs Feet, Meters or Yards as follows:
string convert = "";
do
{
Console.Clear();
Console.WriteLine("What conversion: Feet, Meters, Yards");
try
{
convert = Convert.ToString(Console.ReadLine());
}
catch (Exception)
{
Console.Clear();
Console.WriteLine("Incorrect conversion");
Console.ReadKey();
}
convert = Values.Input(convert);
Console.WriteLine(convert);
Console.ReadKey();
} while (_____); // Trying to loop while argument is thrown from my other class
Console.WriteLine("Continue on");
Console.ReadLine();
My separate values classes Input method:
public static string Input(string input)
{
string convert = input;
if (convert == "Meters")
{
input = "Meters";
}
else if (convert == "Feet")
{
input = "Feet";
}
else if (convert == "Yards")
{
input = "Yards";
}
else
{
throw new System.ArgumentException("Incorrect conversion");
//Trying to loop my main program if an ArgumentException is thrown here
}
return input;
}
What I've attempted:
} while (convert != "Meters" || convert != "Feet" || convert != "Yards");
Console.WriteLine("Continue on");
Console.ReadLine();
I've tried telling it to keep looping while convert is not Meters, Feet or Yards, but after the argument is thrown I am unable to continue the program.
Would I be able to continue my application after throwing this System.ArgumentException and if so what would I input into my while loop to allow this?
The problem is that the position where you call Values.Input() is outside the try/catch statement and when this throws an exception, it is not handled in the catch you've defined. So it will be caught up the callstack. Try placing the Values.Input(..) inside the try/catch statement.
string convert = "";
do
{
Console.Clear();
Console.WriteLine("What conversion: Feet, Meters, Yards");
try
{
convert = Convert.ToString(Console.ReadLine());
// ------- PASTE
convert = Values.Input(convert);
Console.WriteLine(convert);
// -----
}
catch (Exception)
{
Console.Clear();
Console.WriteLine("Incorrect conversion");
}
// XXXXXXXXX CUT
// XXXXXXXXX
Console.ReadKey();
} while (_____); //Trying to loop while argument is thrown from my other class
Console.WriteLine("Continue on");
Console.ReadLine();
This Input() function is pretty wild. What exactly is it doing? Basically nothing. You want to return some determinate value that indicates what type of unit it is, right?
Let's replace it with this:
public enum Unit { Meters, Feet, Yards }
public static Unit Input(string input)
{
switch (input.ToLowerInvariant())
case "meters": return Unit.Meters;
case "feet": return Unit.Feet;
case "yards": return Unit.Yards;
default: throw new System.ArgumentException("Incorrect conversion");
}
}
So after that we can fix the code:
Unit unit;
while (true)
{
Console.WriteLine("What conversion: Feet, Meters, Yards");
try
{
var input = Console.ReadLine();
unit = Values.Input(convert);
break; // if we get here we didn't throw an exception, so we can exit the loop
}
catch
{
Console.WriteLine("Incorrect conversion");
}
}
Console.WriteLine("Continue on");
Console.ReadLine();

C# - How to handle errors in this code using try-catch block?

I have this code:
else if (number == 5)
{
Console.Write("Student's index: ");
int index1 = int.Parse(Console.ReadLine());
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
I need to handle errors using try-catch when the user doesn't enter any character or enters a non-integer character. How can that be done?
Use TryParse to check if the input is an integer or not. Then if it's an integer, do whatever you want with the index.
else if (number == 5)
{
Console.Write("Student's index: ");
var success = int.TryParse(Console.ReadLine(), out int index1);
if (success)
{
//next logic here if the input is an integer
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
else
{
//do something when the input is not an integer
}
}
You need to move your int.Parse line inside the try {} block. Only then will it be in the safety net of structured exception handling. You can then add a second catch {} block against a FormatException see Int32.Parse docs for exceptions thrown.
else if (number == 5)
{
Console.Write("Student's index: ");
try
{
int index1 = int.Parse(Console.ReadLine());
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
catch (FormatException)
{
Console.WriteLine("Error: Index must be a number.");
}
}

Try, Catch can't return correct value

This code aks for input from the user.
I wish to have the user try again after he sends wrong input and triggers any of the exceptions below.
After getInputNumber() is triggered after the exception and the user enters the right input as numbers, the return is then triggered which returns the correct number.
After this return, it returns to the FormatException thus deleting the correct number value and returning only 0.
How can I fix it to get the correct value, but also keep allowing the user to try again if he misses the correct input?
private static int getInputNumber()
{
int number = 0;
try
{
number = Convert.ToInt32(Console.ReadLine());
}
catch (Exception ex)
{
if (ex is FormatException)
{
Console.Clear();
Console.WriteLine("Wrong format! \nTry numbers instead.");
getInputNumber();
}
else if (ex is OverflowException)
{
Console.Clear();
Console.WriteLine("The number you entered is too large.\nTry a number between 1 and 2,147,483,647");
getInputNumber();
}
}
return number;
}
On your catch block try this:
...
if (ex is FormatException)
{
Console.Clear();
Console.WriteLine("Wrong format! \nTry numbers instead.");
return getInputNumber();
}
....
Instead of just calling it. This is because when you call the getInputNumber() method after first catch and it passes successfull, it gets back to your catch block(at this point number is still 0 since a exception occurs)
As stybl said, it's better to use a boolean check and while loop to keep asking for a valid input user.
First of all, I recommend using Int32.Parse instead. It won't make much of a difference in this particular case, but it is considered best practice. For your code to work you need to include return statements for every recursive call of getInputNumber:
private static int getInputNumber()
{
int number = 0;
try
{
number = int.Parse(Console.ReadLine());
}
catch (Exception ex)
{
if (ex is FormatException)
{
Console.Clear();
Console.WriteLine("Wrong format! \nTry numbers instead.");
return getInputNumber();
}
else if (ex is OverflowException)
{
Console.Clear();
Console.WriteLine("The number you entered is too large.\nTry a number between 1 and 2,147,483,647");
return getInputNumber();
}
}
return number;
}
However, making getInputNumber recurse like that is a bad idea. Instead, you should use an infinite loop. The final result will look something like this:
private static int getInputNumber()
{
int number = 0;
while (true)
{
try
{
number = int.Parse(Console.ReadLine());
break;
}
catch (Exception ex)
{
if (ex is FormatException)
{
Console.Clear();
Console.WriteLine("Wrong format! \nTry numbers instead.");
}
else if (ex is OverflowException)
{
Console.Clear();
Console.WriteLine("The number you entered is too large.\nTry a number between 1 and 2,147,483,647");
}
else
{
Console.Clear();
Console.WriteLine("Unexpected error!");
}
}
}
return number;
}

Console app input and output

this is my simple C# console app in this i will get input from user i have postal code variable in which i want to take input as integer but when i input integer it shows error. another approch is that console.readline take both int and string as input or not ??
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string firstname;
string lastname;
string birthdate;
string addressline1;
string adressline2;
string city;
string stateorprovince;
int ziporpostalcode;
string country;
ziporpostalcode =int.Parse(Console.ReadLine());
}
}
}
you should Use int.TryParse instead for int.Parse, Which is
responsible to Converts the string representation of a number to its
32-bit signed integer equivalent. A return value indicates whether the
operation succeeded, else return false(conversion failed)
So your code may looks like this:
int ziporpostalcode;
if (int.TryParse(Console.ReadLine(), out ziporpostalcode))
{
Console.WriteLine("Thank you for entering Correct ZipCode");
// now ziporpostalcode will contains the required value
// Proceed with the value
}
else {
Console.WriteLine("invalid zipCode");
}
Console.ReadKey();
Console.WriteLine("Enter Zip Code");
try
{
ziporpostalcode = int.Parse(Console.ReadLine());
Console.WriteLine("You Enter {0}", ziporpostalcode);
}
catch (Exception) {
Console.WriteLine("Error Occured, Enter only Number");
}
Console.ReadLine();
Suggested way.
Use int.TryParse to validate your input to int.
var input =int.Parse(Console.ReadLine());
if(int.TryParse(input, out ziporpostalcode )
{
// you have int zipcode here
}
else
{
// show error.
}

Categories