如何在try-catch中初始化变量?

时间:2013-10-02 15:45:43

标签: c#

我在try-catch中有一个未初始化的变量。

try
{
    var customcontroldata = svc.queryLookupsXml("customcontroldata");
}
catch
{
    Response.Write(@"<script>alert('We laugh at you');window.location.replace('Accounts.aspx');</script>");
    Response.End();
 }

我试图在try-catch之外初始化变量,但没有完成。我如何在这个方法中初始化customcontroldata变量,后面的代码也会使用它?

4 个答案:

答案 0 :(得分:5)

您需要在try块之外声明变量。您可以将其指定为null,然后在catch之后,在对其执行任何操作之前检查它是否为空。

在这种情况下,您还需要具体说明对象的类型,因为在声明对象时,您将无法将其分配给您想要的最终值,因为这会发生在{{ 1}}。

答案 1 :(得分:3)

        XmlNode customcontroldata = null;
        try
        {
            customcontroldata = svc.queryLookupsXml("customcontroldata");
        }
        catch
        {
           Response.Write(@"<script>alert('We laugh at you');window.location.replace('Accounts.aspx');</                    script>");
            Response.End();
        }

答案 2 :(得分:1)

在您的代码中,customcontroldata的范围在try块中,因此不在该范围之外。尝试在try之外声明它,如下所示......

myObjectType customcontroldata; = null4
try
{
    customcontroldata = svc.queryLookupsXml("customcontroldata");
}
catch
{
    Response.Write(@"<script>alert('We laugh at you');window.location.replace('Accounts.aspx');</                    script>");
    Response.End();
}

答案 3 :(得分:0)

您想要在Try / Catch块之外声明变量,初始化为null / empty值。

你可以在块中进行赋值,但是如果你计划在TryCatch块之外使用它,总是测试变量是否为空/空。