C#異常處理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/* 拋出異常
 * 捕獲異常
 *
 * 異常篩選器的作用
 */

namespace MyApp
{
    class Program
    {
        static double EllArea(double r)
        {
            if (r <= 0)
            {
                throw new ArgumentException("半徑長度不能小於或等於0.");
            }
            return Math.PI * r * r;
        }

        static void DoSomething(string x, string y)
        {
            if (string.IsNullOrEmpty(x))
            {
                throw new ArgumentException("參數不能爲空.","x");
            }
            if (string.IsNullOrEmpty(y))
            {
                throw new ArgumentException("參數不能爲空.", "y");
            }
        }

        static void Main(string[] args)
        {
            try
            {
                double res = EllArea(0d);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.GetType().Name+":"+ex.Message);
            }

            try
            {
                //DoSomething(null, null);
                DoSomething("abc", null);
            }
            catch (ArgumentException ex) when (ex.ParamName == "y")
            {
                Console.WriteLine(ex.GetType().Name+":"+ex.Message);
            }
            catch
            {
                Console.WriteLine("其他異常信息");
            }

            Console.ReadKey();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章