47 异常2

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 抛出异常
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("请输入0-10之间的数");
                int number = Convert.ToInt32(Console.ReadLine());
                if (number < 0 || number > 10)
                {
                    throw new SystemException();
                }
                else
                {
                    Console.WriteLine("你输入的数字为{0}", number);
                }
            }
            catch (SystemException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
             //   Console.WriteLine("输入的数字超出范围");
            }
            finally
            {
                Console.WriteLine("非常好");
            }
        }
    }
}

自定义异常

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 自定义异常
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("请输入一个正数");
                double number = Convert.ToInt32(Console.ReadLine());
                //int root;
                if (number < 0)
                {
                    throw new yichang();
                }
                else
                {
                    double root = Math.Sqrt(number);
                    Console.WriteLine(root);
                }
            }
            catch(yichang e)
            {

                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }
    class yichang:ApplicationException
    {
        public yichang(): base("对负数非法操作")
        {

        }
        public yichang(string str): base(str)
        {
        }
    }
}

 

 

posted on 2013-05-09 21:48  杨柳清枫2012  阅读(76)  评论(0)    收藏  举报

导航