大家都用Try-Catch在 C# 中。我知道。
例如;
static void Main()
{
string s = null; // For demonstration purposes.
try
{
ProcessString(s);
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
一切正常
但是我如何为特定错误指定名称?
例如;
try
{
enter username;
enter E-Mail;
}
catch
{
}
- 如果用户名已经存在,
ErrorMessage
--> ("The Username Already Exist") - 如果电子邮件已经存在,
ErrorMessage
--> ("E-Mail is using")
我如何在 C#
中做到这一点?
最好的问候,
桑纳
最佳答案
if(UserNameAlreadyExists(username))
{
throw new Exception("Username already exists");
}
if(EmailAlreadyExists(email))
{
throw new Exception("Email already exists");
}
这将回答您的问题。
但异常处理不用于执行此类检查。异常代价高昂,适用于无法从错误中恢复的特殊情况。
关于C# 为 Try-Catch 错误分配名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5349276/