调用对象时出现未处理的异常

时间:2017-03-13 17:22:24

标签: c# .net unhandled-exception

我构建了以下类:

   public class FSCServerLocator
    {
        public string userLocation { get; private set; }

        public string FSCServer
        {
            get
            {
                switch (userLocation)
                {
                    default:
                        return @"\\himgwsfs01\QT_Tools\Diagnose\09_SWT_FSCs";
                }
            }
        }

        public FSCServerLocator(string location)
        {
            if (string.IsNullOrWhiteSpace(userLocation))
            {
                throw new Exception("No location included at initialization");
            }
            //parameter filtering
            userLocation = location;
        }
    }
}

并像这样调用对象

var fscServerLocator = new FSCServerLocator(@"\\himgwsfs01\QT_Tools\Diagnose\09_SWT_FSCs");

运行程序时会抛出一个未处理的异常,说{"No location included at initialization"}。 我只是想看看是否到达了位置,但也许我错过了一些东西,因为我是c#

的新手

2 个答案:

答案 0 :(得分:5)

您需要更改构造函数以查看位置而不是 userLocation (见下文),以避免此异常:

    public FSCServerLocator(string location)
    {
        if (string.IsNullOrWhiteSpace(location))
        {
            throw new Exception("No location included at initialization");
        }
        //parameter filtering
        userLocation = location;
    }

答案 1 :(得分:0)

    public FSCServerLocator(string location)
    {
        //parameter filtering
        userLocation = location;
        if (string.IsNullOrWhiteSpace(userLocation))
        {
            throw new Exception("No location included at initialization");
        }
    }

    public FSCServerLocator(string location)
    {
        if (string.IsNullOrWhiteSpace(location))
        {
            throw new Exception("No location included at initialization");
        }
        //parameter filtering
        userLocation = location;
    }

在构造函数中设置对象之前,您正尝试使用该对象的参数。您可以先设置它,也可以根据要设置的参数进行测试。