异常处理与自定义异常学习笔记
1
public class Person
2
{
3
private int _age;
4
public int Age
5
{
6
set {
7
if (value < 0 || value > 150)
8
{
9
throw new AgeFormatException("年龄输入不对!");
10
}
11
else
12
{
13
this._age = value;
14
}
15
}
16
get { return this._age; }
17
}
18
public class AgeFormatException : FormatException //自定义异常
19
{
20
public AgeFormatException()
21
: base()
22
{ }
23
public AgeFormatException(string message)
24
: base(message)
25
{ }
26
27
}
28
public static void Main(string[] args)
29
{
30
Person p = new Person();
31
while (true)
32
{
33
try
34
{
35
Console.WriteLine("请输入年龄:");
36
int intAge = Convert.ToInt32(Console.ReadLine());
37
p.Age = intAge;
38
Console.WriteLine("此人的年龄:" + p.Age);
39
}
40
catch (OverflowException oex)
41
{
42
throw oex;
43
}
44
catch (FormatException fex)
45
{
46
throw fex;
47
}
48
catch (Exception ex)
49
{
50
throw ex;
51
}
52
}
53
}
54
}
public class Person 2
{3
private int _age;4
public int Age5
{6
set {7
if (value < 0 || value > 150)8
{9
throw new AgeFormatException("年龄输入不对!");10
}11
else12
{13
this._age = value;14
}15
}16
get { return this._age; }17
}18
public class AgeFormatException : FormatException //自定义异常19
{20
public AgeFormatException()21
: base()22
{ }23
public AgeFormatException(string message)24
: base(message)25
{ }26
27
}28
public static void Main(string[] args)29
{30
Person p = new Person();31
while (true)32
{33
try34
{35
Console.WriteLine("请输入年龄:");36
int intAge = Convert.ToInt32(Console.ReadLine());37
p.Age = intAge;38
Console.WriteLine("此人的年龄:" + p.Age);39
}40
catch (OverflowException oex)41
{42
throw oex; 43
}44
catch (FormatException fex)45
{46
throw fex;47
}48
catch (Exception ex)49
{50
throw ex;51
}52
}53
}54
} 
