未处理 C# 异常

本文关键字:异常 未处理 | 更新日期: 2024-11-05 20:50:54

目前正在处理一个小项目,其中包括一个注册表表单,用户可以在其中注册登录。我有错误提供程序,它会告诉用户他们输入的信息是否正确。由于某种原因,不再处理异常,即使它们是一段时间前。

这是用户按下"注册按钮"时的代码

private void btnRegister_Click(object sender, EventArgs e)
{
    //Try - Catch Statements
    //Try to set the forename 
    try
    {
        player1.Forename = txtForename.Text;
        player2.Forename = txtForename.Text;
        errForename.Icon = Properties.Resources.Correct;
        errForename.SetError(txtForename, "OK");
    }
    catch (NewException exc)
    {
        errForename.SetError(txtForename, exc.MessageM);
    }

然后,它会对其他详细信息执行此操作,例如姓氏、用户名。

这是用户类获取者和设置者

public string Forename
{
    get
    {
        return forename;
    }
    set
    {
        bool okChar = OnlyChars(value, "Forename");
        if (okChar == true)
            forename = value;
        else
        {
            throw new NewException(errorMessage);
            forename = null;                        
        }
    }
}

最后是我写的NewException类

namespace Colludia
{
    class NewException : Exception
    {
        private string messageM;
        public NewException() : base()
        {    
        }
        public NewException(string message) : base(message)
        {
            messageM = message;    
        }
        public string MessageM
        {
            get { return messageM; }
            set { messageM = value; }
        }
    }
}

未处理 C# 异常

这是适合您的工作代码。我认为它的命名空间问题

using System;
class Player
{
    string forename = "";
    string errorMessage = "";
    public string Forename
    {
        get
        {
            return forename;
        }
        set
        {
            bool okChar = OnlyChars(value, "Forename");
            if (okChar == true)
                forename = value;
            else
            {
                throw new NewException(errorMessage);
            }
        }
    }
    private bool OnlyChars(string value, string p)
    {
        if (value == p)
            return true;
        else
        {
            errorMessage = "Err";
            return false;
        }
    }
}
class NewException : Exception
{
    private string messageM;
    public NewException()
        : base()
    {
    }
    public NewException(string message)
        : base(message)
    {
        messageM = message;
    }
    public string MessageM
    {
        get { return messageM; }
        set { messageM = value; }
    }
}
class Program
{
    static void Main(string[] args)
    {
        try
        {
            var player1 = new Player();
            var player2 = new Player();
            player1.Forename = "asdfg";
            player2.Forename = "qwerty";
        }
        catch (NewException exc)
        {
            bool error = true;
        }
    }
}