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();
        }
    }
}

 

你可能感兴趣的:(C#基础,异常处理,C#)