C# C# Basics (Retired) Perfect Final

Christian Higgins
Christian Higgins
15,514 Points

Confused about what to put inside the try/catch areas

I don't understand why this part goes inside the try area:

Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
int count = int.Parse(input);

To me, the input is when you would read what the user inputs, and then if it's valid, THEN you go to the try area. If it isn't valid, then you go to the catch. Clearly I'm wrong about this but just seeing if anyone can help me understand why.

1 Answer

Kevin Gates
Kevin Gates
13,212 Points

Hi there,

So Try-Catch is a clever way to test out code that may fail. So looking at this:

Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
int count = int.Parse(input);

There is one area that code go wrong, and it's the Parsing method. Why? Because the input will be a string, and if the user writes "Book" instead of a number, the application will fail.

Therefore, you are better served by this:

Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
try
{
   int count = int.Parse(input);
}
catch (error)
{
   Console.WriteLine(error);
}

Again, the reason is that the code likely to fail is the parse method. Therefore you want to "try" that. And if it fails, you want to "catch" the error, so it fails gracefully.

Christian Higgins
Christian Higgins
15,514 Points

That does make sense, thank you. I have to change the way I think about try/catch. In my mind, I've thought if it ask an if/else. (e.g., if it works, do this (try), if it doesn't work do that (catch).

Kevin Gates
Kevin Gates
13,212 Points

Hi Christian,

The best way to approach If/Else is if you get different working (non-errors) options returned and you're trying to figure out if you get A, do path-A, and if you get B, do Path B.

Try/ Catch is more if you get A-Z, great. If it blows up and you don't get A-Z back, send this error and perform this action.