C# 为 Try-Catch 错误分配名称

标签 c# error-handling try-catch

大家都用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/

相关文章:

c# - 将 WinForm ContextMenu 背景设为灰色?

c# - 在Azure API for VM中,是否有一种方法可以用一种方法定义许多现有的数据磁盘?

c# - 如何将日期时间字段值设置为现在

PHP 捕获 undefined variable 错误

时间:2019-05-17 标签:c#webapiowinauthentication

java - 如何解决未封闭字符类错误

powershell - 在Powershell中导出大型嵌套对象以便以后进行测试/模拟的最佳方法是什么?特别是Http和Web异常

python - 当我只想要Y和N时如何错误陷阱其他字母?

java - Try、Catch 和 Finally block

python - Python中如何用冗余代码更好地编写多个异常?