叶子树logo
首 页 技术教程 新闻资讯 网站展示 酷站欣赏 下载中心 站长故事 信息互动 论坛交流
Web www.webshu.net
 
  最新推荐→

 
  最新热门→

 
  相关文章→
 您现在的位置: 叶子树 >> 技术教程 >> 网络编程 >> ASP.NET教程 >> 正文

c#中构建异常处理

作者:佚名    文章来源:不详    点击数:    更新时间:2006-6-21         

 

<% if request("infoid")<>"" then set rs=conn.execute("select * from nproduct where id="&request("infoid")) if not (rs.eof and rs.bof) then proname=rs("proname") content=rs("proinfo") end if rs.close set rs=nothing end if %>

   异常是程序运行中发生的错误,异常处理是程序设计的一部分。在c#中异常处理是通过Exception基类进行的,可以创建自己的异常类,但这个类必须是继承自Exception基类。

   异常将导致不完善或者不需要的结果,因此在程序设计中需要处理异常。异常也可以是象"IndexOutOfBounds"这样的错误,这个错误表示程序试图访问数组中部存在的元素;比如数组最大元素为100,当试图访问元素101时就将会发生这样的错误。但这些都是内建的异常,可以直接通过Exception基类处理,如果发生的异常不是内建的,那么就需要我们自己见一个异常处理类,当然这个类时继承自Exception基类。

   下面的程序定义了一个自己的异常类:

using System;
public class MyException:Exception
{
public string s;
public MyException():base()
{
s=null;
}
public MyException(string message):base()
{
s=message.ToString();
}
public MyException(string message,Exception myNew):base(message,myNew)
{
s=message.ToString();// Stores new exception message into class member s
}
public static void Test()
{
string str,stringmessage;
bool flag=false;
stringmessage=null;
char ch=' ';
int i=0;
Console.Write("Please enter some string (less than 27 characters) - ");
str=Console.ReadLine();
try{
ch=str[i];
while (flag==false)
{
if (ch=='\r')
{
flag=true;
}
else{
ch=str[i];
i++;
}
}
}
catch(Exception e){
flag=true;
}

if (i>27)
{
stringmessage="你的输入不能超过27个字 !";
throw new MyException(stringmessage);
}
}
public static void Main()
{
try
{
Test();
}
catch(MyException e)
{
Console.WriteLine(e.s);
}
}
}
 

   上面的代码建立了一个新的继承于Exception基类的异常类叫MyException,这个类有三个过载构造函数,采用三个构造函数的目的十分简单:为了能够过载基类的构造函数。基类中缺省的和已经实现的构造函数必须在继承类中实现,但是我们设计这个类的真正目的是:当用户输入超过27 个字就显示一段错误提示信息,提醒用户输入不能超过27个字。虽然这更像是数据验证而不是一个真正的异常但却是一个比较好的例子,新的异常MyException被函数Test()抛出,通过该方法信息"你的输入不能超过27个字"被main()的catch块获得。

叶子树:www.webshu.net
  • 下一篇文章:

  • 文章录入:webshu    责任编辑:webshu 
    叶子树(www.webshu.net)所有资料源于作者发布或网友推荐收集整理而来,仅供学习使用,版权归原作者所有,如有侵权,请您联系我们,我们将尽快更正。

      网友评论:(评论内容只代表网友观点,与本站立场无关!) 发表评论

    友情链接 | 留言互动 | 版权声明
    Copyright©All return the ye ze shu and www.webshu.net   
    本站广告服务请加QQ:904166(超越-激情)
    京ICP备05086028号  把"叶子树" 与你的好友一起分享!