Throw C # format exception

I am trying to create a format exception in an instance when someone tries to enter a non-integer character when prompted for their age.

Console.WriteLine("Your age:"); age = Int32.Parse(Console.ReadLine()); 

I am not familiar with C # and can use help writing a catch try block for this instance.

Thank you very much.

+4
source share
4 answers

This code already throws a FormatException . If you mean that you want to catch him, you can write:

 Console.WriteLine("Your age:"); string line = Console.ReadLine(); try { age = Int32.Parse(line); } catch (FormatException) { Console.WriteLine("{0} is not an integer", line); // Return? Loop round? Whatever. } 

However, it would be better to use int.TryParse :

 Console.WriteLine("Your age:"); string line = Console.ReadLine(); if (!int.TryParse(line, out age)) { Console.WriteLine("{0} is not an integer", line); // Whatever } 

This eliminates the exception for a rather unpredictable case of user error.

+20
source

How about this:

 Console.WriteLine("Your age:"); try { age = Int32.Parse(Console.ReadLine()); } catch(FormatException e) { MessageBox.Show("You have entered non-numeric characters"); //Console.WriteLine("You have entered non-numeric characters"); } 
+3
source

You do not need to have a catch try block for this code:

 Console.WriteLine("Your age:"); int age; if (!Integer.TryParse(Console.ReadLine(), out age)) { throw new FormatException(); } 
0
source

dataGridView1.Rows [n] .Cells ["dgAmount"]. Value = float.Parse (item ["Amount"]. ToString ()); FormatException not handled. The input string was in the wrong format. Suggest the correct syntax

0
source

Source: https://habr.com/ru/post/1435722/


All Articles