当代码中有finally块时,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApplication13
{
enum Orientation : byte
{
North = 1,
South = 2,
East = 3,
West = 4
}
class Program
{
static void Main(string[] args)
{
Orientation myDirection;
for (byte myByte = 2; myByte < 10; myByte++)
{
try
{
myDirection = checked((Orientation)myByte);
if ((myDirection < Orientation.North) || (myDirection > Orientation.West))
{
throw new ArgumentOutOfRangeException("Value must between 1 and 4");
}
}
catch (ArgumentOutOfRangeException e)
{
WriteLine(e.Message);
WriteLine("myDirection is assigned by default value, North");
myDirection = Orientation.North;
}
finally
{
WriteLine($" mydirection = {myDirection}");
}
ReadKey();
}
}
}
}
这时 WriteLine($" mydirection = {myDirection}");显示myDirection未赋值。
但是当将
finally
{
WriteLine($" mydirection = {myDirection}");
}
改为只剩下
WriteLine($" mydirection = {myDirection}");
时,就可以正常运行了。
不清楚这个checked((Orientation)myByte)为什么在有finally块的时候没有成功赋值
catch (ArgumentOutOfRangeException e)
修改为
catch (Exception e)
如果丢出别的异常,那么不会走catch,导致myDirection = Orientation.North;并没有执行
另外Orientation myDirection;这里没有初始化是不能编译的
可以用Orientation myDirection = Orientation.xxx; //任意选一个
try{} catch{} finally{} : In try{ } block , if here have a error row data, it will goto catch{} block if the error type is same with catch{error type},
if the error type not exist in catch{},it will goto finnaly{} block,so,the easy way is update "catch (ArgumentOutOfRangeException e)" to "catch
(Exception e)" to let catch{} block accept all error type,so, surely mydirection validate is have a value.