L733 2018-03-29 12:32 采纳率: 100%
浏览 1279
已采纳

C#中try...catch...finally初学,一个变量显示没有赋初始值?

当代码中有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块的时候没有成功赋值

  • 写回答

3条回答 默认 最新

  • threenewbee 2018-03-29 12:48
    关注

    catch (ArgumentOutOfRangeException e)
    修改为
    catch (Exception e)

    如果丢出别的异常,那么不会走catch,导致myDirection = Orientation.North;并没有执行

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序