Skip to content

Commit 55a707c

Browse files
ClémentClément
authored andcommitted
Adding program demonstrating parse w/ exceptions.
1 parent 7953616 commit 55a707c

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

  • source/code/projects/ExceptionParse/ExceptionParse
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using System;
2+
3+
class Program
4+
{
5+
static void Main()
6+
{
7+
string answer;
8+
int value = 0;
9+
bool valid = false;
10+
11+
Console.WriteLine("Test with" +
12+
"\n\t- nothing (ctrl + d on linux, ctrl + z on windows), " +
13+
"\n\t- \"No\"," +
14+
"\n\t- " + int.MaxValue + "+ 1 = 2147483648.");
15+
// Illustrating the exceptions int.Parse can throw.
16+
answer = Console.ReadLine();
17+
18+
try
19+
{
20+
value = int.Parse(answer);
21+
valid = true;
22+
}
23+
catch (ArgumentNullException)
24+
{
25+
Console.WriteLine("No argument provided.");
26+
}
27+
catch (FormatException)
28+
{
29+
Console.WriteLine("The string does not contain only number characters.");
30+
}
31+
catch (OverflowException)
32+
{
33+
Console.WriteLine("The number is greater than what an integer can store.");
34+
}
35+
finally{
36+
Console.WriteLine("You entered \"" + answer + "\".");
37+
38+
if(valid){
39+
Console.WriteLine("I can convert this to the following numerical value:" + value);
40+
}
41+
else{
42+
Console.WriteLine("I cannot convert this to a numerical value.");
43+
}
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)