簡體   English   中英

自定義格式異常 c# - 未處理異常,為什么?

[英]Custom Format Exception c# - exception is being unhandled, why?

我嘗試對以下代碼使用自定義異常。
當用戶輸入一個字符串而不是 int 數字時,它應該顯示來自AgeException的消息。 但它顯示了一個未處理的異常。

class Program
    {
        static void Main(string[] args)
        {
            try {
                Console.WriteLine("Enter Your Age: ");
                int age = Convert.ToInt32(Console.ReadLine());

                if(age>40 || age<6){
                     throw new AgeException(age);
                   }
                else{
                     Console.WriteLine("Your age is :"+age);
                   }
                
            }

            // when (ex.Message.Length>50)
            catch(AgeException ex) //when (ex.Message.Length>15)
            {
                //throw ex;
                Console.WriteLine("Errorrrrr from Age exception class: "+ex.Message);
                Console.ReadLine();
            }
            //catch(Exception ex)
            //{
            //     Console.WriteLine(ex.Message);
            //    Console.WriteLine("\n\n"+ex.StackTrace);
                
            //}


            Console.ReadLine();
        }
    }

    class AgeException : FormatException
    {
        private int messageDetails;
        // private string messageage;

        public AgeException() {        }
        public AgeException(int age) : base(String.Format("Invalid Student AGe: {0}", age))
        {
            messageDetails = age;
        }
        
       public override string Message => $"Invalid age: {messageDetails}";
        //public override string Message => $"Invalid age: {messageage}";

    }```


  [1]: https://i.stack.imgur.com/YmWay.png

您可以檢查用戶是否只輸入數字

    Console.WriteLine("Enter Your Age: ");
    int age;
    
    while(!int.TryParse(Console.ReadLine(), out age))
    {
         Console.Clear();
         Console.WriteLine("You entered an invalid number");
         Console.Write("Enter Your Age: ");
    }

    if(age>40 || age<6){
           throw new AgeException(age)
    }
    else{
        Console.WriteLine("Your age is :"+age);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM