C#学习笔记四

来源:互联网 发布:网络文明正能量 编辑:程序博客网 时间:2024/06/10 03:04

 学到异常处理,书上以Email验证为例子,我觉得限制的不够,现在就写下。

1.首先自定义一个异常:EmailErrorException,继承自System.ApplicationException

using System;
using System.Collections.Generic;
using System.Text;

namespace EmailValidate
{
    class EmailErrorException:System.ApplicationException
    {
       public EmailErrorException(string message):base(message)
       {
       }
    }
}

2.建一个验证类,其中验证方法:EmailValidate()

public void EmailValidate(string email)
        {
            try
            {
                this._email = email;
                //以@为界线将email字符串分割为一个长度为2的字符数组
                string[] em1 = _email.Split('@');
                //试着以@为界线将em1[0]分为一个长度为2的数组.
                //如果操作成功即数组长度为2,则表示Email不规范。
                string[] em2 = em1[0].Split('@');
                if (em1.Length != 2)
                    throw new EmailErrorException("Email中应该包括'@'");
                else
                {
                    int index = em1[1].IndexOf('.');
                    string[] em3 = em1[1].Split('@');
                    if (em2.Length == 2 || em3.Length == 2)
                        throw new EmailErrorException("Email中只能有一个'@'");
                    //如果在@后面的字符串中没有"."或者在第一一位,则引发异常。
                    if (index <= 0)
                        throw new EmailErrorException("不存在'.'或者在'@'后第一位");
                    //如果"."在最后一位,则引发异常。
                    if (em1[1][em1[1].Length - 1] == '.')
                        throw new EmailErrorException("'.'不能在Email的最后一位");
                    //如果在@后面的字符串中有两个连续的".",则引发异常。
                    if (em1[1][index + 1] == '.')
                        throw new EmailErrorException("两个'.'不能连续写在一起");
                }
            }
            catch (EmailErrorException em)
            {
                MessageBox.Show(em.Message);
            }
        }

当然还有一些情况没有限制到,如:123@tom.,com