[C#每天进步一点点] 异常该注意的几点
1.catch子句按照筛选器的继承层次进行顺序罗列,否则将导致编译错误
示例:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace ExceptionTest
6 {
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 try
12 {
13 throw new NullReferenceException();
14 }
15 catch (Exception)
16 {
17 }
18 catch (NullReferenceException)
19 {
20 }
21 }
22 }
23 }
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace ExceptionTest
6 {
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 try
12 {
13 throw new NullReferenceException();
14 }
15 catch (Exception)
16 {
17 }
18 catch (NullReferenceException)
19 {
20 }
21 }
22 }
23 }
编译结果为:
Error 1 A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')...
2.try块内定义的变量对try块 外是不可见的,对于try块内进行初始化的变量应该定义在try块之前,否则将导致编译错误。
示例:
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
namespace ExceptionTest
{
class Program
{
static void Main(string[] args)
{
try
{
int i = 0;
}
catch (Exception)
{
Console.WriteLine(i);
}
}
}
编译结果为:
Error 1 The name 'i' does not exist in the current context ...