C#使用throw抛出异常


C#使用throw抛出异常

如下面所示,虽然输入的值是一个整数,但是如果输入超过了150,显然超出了人类目前的极限,所以可以再次使用throw抛出异常

using System;
namespace HxRuntech
{
    public class T1
    {
        static void Main()
        {
            string? ageText;
            int? age;
            Console.Write("Enter you age:");
            ageText = Console.ReadLine();

            try
            {
                age = int.Parse(ageText!);

                if(age > 150)
                {
                    throw new Exception($"{age} is too big for human being");
                }
                Console.WriteLine(age);
            }
            catch (Exception ex) { 
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("Good bye");
            }
        }
    }
}