2016-04-30 53 views
0

我想了解我的代碼有什麼問題,因爲它不會向用戶顯示錯誤消息。謝謝你的建議。如何在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;    
    } 
+0

你必須把'Console.WriteLine(「文字輸入失敗子程序AskString」);''之前拋出新的System.Exception(「參數不能爲空」) ;'因爲一旦拋出異常就會離開if範圍。意思是程序永遠不會達到你的錯誤信息。 此外,阿列克謝關於空/空白檢查有一個很好的觀點。 – Cicero

回答

3

拋出應用程序執行後會停止,所以你的消息不會出現。

更改代碼

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

而且,當你把新的異常,它必須處理在另一個地方。如果你不這樣做,你的應用程序會崩潰

1

你trowing未在您的應用程序的任何更高層次處理的異常(所以你不會看到任何東西)。投擲後的代碼在任何情況下都不會因爲投擲而達到。