c exception handling example sharing

  • 2020-06-15 10:07:32
  • OfStack


using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
//2014.3.14
namespace _6. abnormal 
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Convert before ");
                int a = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Convert after ");
            }
            catch (Exception ex)
            {
                Console.WriteLine(" Input error: "+ex.Message+" Exception stack: "+ex.StackTrace);
            }

            try
            {
                Console.WriteLine(" Please enter your age: ");
                int s = Convert.ToInt32(Console.ReadLine());
                string desc = GetAgeDesc(s);
                Console.WriteLine(desc);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" Data error, "+ex.Message);
            }
             Console.ReadKey();
        }

        static string GetAgeDesc(int age)
        {
            if (age >= 0 && age <= 3)
            {
                return " Infants and young children ";
            }
            else if (age > 3 && age < 18)
            {
                return " teenagers ";
            }
            else if (age >=18 && age < 60)
            {
                return " adults ";
            }
            else if (age >= 60 && age < 100)
            {
                return " The elderly ";
            }
            else
            {
                throw new Exception(" Self-Created ex.Message");
            }
        }
    }
}

Related articles: