我想了解我的代碼有什麼問題,因爲它不會向用戶顯示錯誤消息。謝謝你的建議。如何在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;
}
你必須把'Console.WriteLine(「文字輸入失敗子程序AskString」);''之前拋出新的System.Exception(「參數不能爲空」) ;'因爲一旦拋出異常就會離開if範圍。意思是程序永遠不會達到你的錯誤信息。 此外,阿列克謝關於空/空白檢查有一個很好的觀點。 – Cicero