【问题标题】:Error string in catch block? [closed]catch 块中的错误字符串? [关闭]
【发布时间】:2010-07-22 10:53:36
【问题描述】:

我有以下代码在出现错误时显示字符串中的错误

有什么办法可以让我在 catch 块中做到这一点?

  main()
    {
    try
    {
    if (a==1)
    {
     string = "error1"
    }
    elseif (a==2)
    {
     string = "error2"
    }
    }
    }
    catch (e)
    {


    }

如下:

我有以下代码在出现错误时显示字符串中的错误

有什么办法可以让我在 catch 块中做到这一点?

main()
{
try
{
}
}

catch (e)
{

if (a==1)
{
 string = "error1"
}
elseif (a==2)
{
 string = "error2"
}

}

【问题讨论】:

  • 这是什么鬼?请重写所有代码并再次发布。那不是 C#。
  • 如果这段代码真的是 C#(你需要一个 try 语句加上其他一些东西)那么它会工作假设在引发异常时设置了 a 的值并且你的 @987654325 @ 变量在 try 之外声明。

标签: c# .net asp.net


【解决方案1】:

恐怕您正在对语法进行绝对散列。我建议您先阅读MSDN article on try-catch statements。异常处理的语法和语义应该开始变得有意义了。

【讨论】:

    【解决方案2】:

    即使它是一个不正确的版本,它也可以很好地回答你的问题:

        try {
    
            if (a == 1) {
                throw new Exception("error1");
            } else if (a == 2) {
                throw new Exception("error2");
            }
    
        } catch (Exception ex) {
            Console.WriteLine("Errormessage = " + ex.Message);
        }
    

    【讨论】:

      【解决方案3】:

      为什么要将逻辑放入 catch 块中?

      您应该阅读异常处理以了解正确的语法是什么,以及为什么要首先使用它。

      http://www.csharp-station.com/Tutorials/lesson15.aspx

      一本关于c#的好书也可能有用,你可以试试Essential C#,因为它对初学者很有用...

      【讨论】:

        【解决方案4】:

        这不是使用异常处理的正确方法。 异常应该是异常的,而不是用于条件逻辑。

        你只需要你的 if ... else 块。

        【讨论】:

          【解决方案5】:

          你可能想做这样的事情。

           try {
          
           if(a == 1) {throw new Exception("Erorr1");}
          
           if(a == 2) {throw new Exception("Erorr2");}
          
           } catch(Exception e) {
             /*Do something with exception or look below */
           }
          

          在这里,您通过抛出一个在 catch 子句中提供的异常来引发错误

          或者这个

          try{
           /*Some code that cause an Exception*/
          } catch(Exception e) { //Exception describe the type which wold be caught. 
          
           string errorType = String.Empty;
          
           var a = -1; //Assign to it smtg from e that You want to check
          
           if(a == 1) {
             errorType = "erro1";
           }
           else  if (a == 2) {
             errorType = "erro2";
           }
          
           /* More Your code*/
          
          }
          

          hire 你用你发现的错误类型做某事。

          但首先要了解您想在代码中使用的内容。

          【讨论】:

          • 这可能是使用异常的最糟糕的做法。根据变量的值做出决定并不是应该抛出异常的原因,而是应该使用“if”语句的原因。
          • 这是一种值得商榷的做法,例如,当我们有 null 时,某个字段/参数系统在我们尝试使用它时会抛出错误,但如果我们在控制台上显示该 null 则不会发生任何错误。在一些复杂的算法中,计算也可以以这种方式停止。尽管如此,我们只能假设 SmartestVEGA 想要什么。
          【解决方案6】:

          阅读Baseball Exception Handling 以及为什么不这样做。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-09-27
            • 1970-01-01
            • 2015-02-25
            • 1970-01-01
            • 1970-01-01
            • 2013-12-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多