如何在 C# 中抛出错误消息?

How to throw an error message in C#?

我想了解我的代码有什么问题,因为它没有向用户显示错误消息。谢谢你的建议。

   public class Program
   {
      static void Main (string[] args)  {
      Console.WriteLine("Please, input some text");
      string name = Console.ReadLine();
      Console.WriteLine(AskString(name));
      Console.ReadLine();        
    }

     public static string AskString(string greeting)
    {
        if (greeting == "")
        {
            throw new System.Exception("Parameter cannot be null");                
            Console.WriteLine("Text input failed in subroutine AskString");
        }

        return greeting;            
    }

很可能,greeting == "" returns 错误。尝试 String.IsNullOrWhiteSpace 而不是忽略 CR 或 LF 等字符。

您抛出的异常未在您的应用程序的任何更高级别处理(因此您将看不到任何内容)。 throw之后的代码无论如何都不会因为throw.

抛出后应用程序将停止执行,因此不会出现您的消息。

更改您的代码

 Console.WriteLine("Text input failed in subroutine AskString"); 
throw new System.Exception("Parameter cannot be null");                

另外,当你抛出新的异常时,它必须在另一个地方处理。如果您不这样做,您的应用程序将会崩溃