46 异常

  try -catch

try -catch - finally

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

namespace 异常
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入分母");
            try
            {
                int a = Convert.ToInt32(Console.ReadLine());
                double result = 0 / a;
                Console.WriteLine(result);
            }
            catch (DivideByZeroException)
            {
                Console.WriteLine("分母不能为零");
            }
            catch (FormatException)
            {
                Console.WriteLine("请输入数字");
            }
             finally
                {
                    Console.WriteLine("运行了finally");
                }
        }
    }
}


throw

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 IndexOutOfRangeException();
                }
                else
                {
                    Console.WriteLine("你输入的数字为{0}", number);
                }
            }
            catch (IndexOutOfRangeException)
            {

                Console.WriteLine("输入的数字超出范围");
            }
            finally
            {
                Console.WriteLine("非常好");
            }
        }
    }
}

 

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

导航