CSharp2023
CSharp2023

Reputation: 1

How do I run this code without using try catch?

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.

Upvotes: 0

Views: 61

Answers (1)

Akash Harale
Akash Harale

Reputation: 31

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

Upvotes: 3

Related Questions