自定义异常

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    
public class Program
    {
        
static void Main(string[] args)
        {

            
try
            {
                Console.WriteLine(
"请输入一个非负数:");

                
int number = Convert.ToInt32(Console.ReadLine());

                
double root;

                
if (number < 0)
                {
                    
throw new NegativeNumberException("负数不能开平方!");
                }
                
else
                {
                    root 
= Math.Sqrt(number);
                }

                Console.WriteLine(
"结果:{0}", root);
            }
            
catch (FormatException e)
            {
                Console.WriteLine(
"Message:{0}", e.Message);
                Console.WriteLine(
"StackTrace:{0}", e.StackTrace);
            }
            
catch(NegativeNumberException e)
            {
                Console.WriteLine(
"Message:{0}",e.Message);
                Console.WriteLine(
"StackTrace:{0}",e.StackTrace);
            }
           
        }
    }

    
public class NegativeNumberException:ApplicationException
    {
        
public NegativeNumberException(): base("对负数非法操作!")
        {
 
        }

        
public NegativeNumberException(string message): base(message)
        { 
            
        }


    }

}

 

  当我们编写程序时,先在.Net中寻找是否有现成的异常类可用,如果有就直接使用.Net中的异常类,如果没有,就创建新的异常类.

 

posted @ 2010-09-09 15:10  唔愛吃蘋果  阅读(214)  评论(0编辑  收藏  举报