泛化catch

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

namespace ExceptionHandling
{
    class Program
    {
        static int Main(string[] args)
        {
            string firstNamne;
            string ageText;
            int age;
            int result = 0;

            while (true)
            {
                
                Console.WriteLine("Enter your first name: ");
                firstNamne = Console.ReadLine();

                Console.Write("Enter your age: ");
                ageText = Console.ReadLine();

                Console.Clear();

                try
                {
                    age = int.Parse(ageText);
                    Console.WriteLine(
                        "Hi{0}! You are {1} months old.", firstNamne, age * 12);
                }
                catch (FormatException)
                {
                    Console.WriteLine(
                        "The age entered,{0},is not valid.", ageText);
                    result = 1;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(
                        "Unexcepected error: {0}", exception.Message);
                    result = 1;
                }
                catch
                {
                    Console.WriteLine("Goodbye {0}", firstNamne);
                }

                finally
                {
                    Console.WriteLine("Goodbye {0}", firstNamne);
                }
            }
            
            return result;
        }
    }
}
    泛化catch可以指定一个不获取任何参数的catch块,没有指定数据类型的catch块称为泛化catch块(generic catch block),它等价于获取object数据类型的catch块,例如catch(object exception){...}。由于所有类最终是从object派生,所以没有数据类型的catch块必须出现在最后。

    泛化catch块很少使用,因为没有办法捕捉有关异常的任何信息。除此之外,C#不允许引发object类型的一个异常,只有使用C++这样的语言写的库才允许任意类型的异常。

posted @ 2012-12-25 16:29  陳さん様  阅读(117)  评论(0编辑  收藏  举报