【发布时间】:2016-08-22 14:13:46
【问题描述】:
我制作了这个程序,它是一种猜谜游戏,除了一件事外,它都运行良好。我创建了一个自定义异常来检查输入类型是否仅为字母类型。我已经对其进行了测试,它确实按预期抛出了异常,但我希望异常在它的消息中显示用户键入的字符导致异常。这样做的最佳方法是什么?这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Test {
class Hangman
{
static void Main(string[] args)
{
string hiddenWord = "chivarly";
string placeHolder;
char[] a = new char[hiddenWord.Length];
for (int i = 0; i < a.Length; i++)
{
a[i] = '*';
}
for (int i = 0; i < a.Length; i++)
{
Console.Write(a[i] + " ");
}
Console.WriteLine("Welcome try to guess my word!");
int count = 0;
do
{
Console.WriteLine("Enter your guess letter");
char input = Console.ReadLine().ToCharArray()[0];
placeHolder = Convert.ToString(input);
try
{
bool isCharLetter = CheckLetter(placeHolder);
}
catch(NonLetterException x)
{
WriteLine(x.Message);
WriteLine(x.StackTrace);
}
for (int i = 0; i < hiddenWord.Length; i++)
{
if (hiddenWord[i] == input)
{
count++;
a[i] = input;
for (int j = 0; j < a.Length; j++)
{
Console.Write(a[j] + " ");
}
}
}
Console.WriteLine();
}
while (count < a.Length);
Console.WriteLine("You have won, HUZZAH!");
Console.ReadLine();
}
static bool CheckLetter(string questionedChar)
{
bool decision = false;
foreach(char c in questionedChar)
{
if(!char.IsLetter(c))
{
decision = false;
NonLetterException nle = new NonLetterException();
throw (nle);
}
else
{
decision = true;
}
}
return decision;
}
}
class NonLetterException : Exception
{
private static string msg = "Error input string is not of the alpahbet. ";
public NonLetterException() : base(msg)
{
}
}
}
【问题讨论】:
-
Exception是一个类,您需要确保在一天结束时传递您想要显示层次结构的任何信息 -
一个常见的方法是使用
innerException
标签: c# visual-studio oop exception-handling