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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog