天天看點

異常

異 常 異常 異常

1.異常

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

namespace CSharp基礎文法
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                int a = Convert.ToInt32("123ass");
                Console.WriteLine("結果:" + a);

            }catch(Exception e)
            {
                Console.WriteLine("出錯:" + e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }
}


           

2.自定義異常

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

namespace CSharp基礎文法
{
    class NotFoundException:Exception
    {
        public NotFoundException()
        {

        }
        public NotFoundException(string message) : base(message)
        {

        }
    }
}

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

namespace CSharp基礎文法
{


    class Program
    {
        public static void find(int a)
        {
            if (a < 0)
            {
                throw new NotFoundException(a + "不存在");
            }
        }
        static void Main(string[] args)
        {


            find(-100);
        }
    }
}


           

繼續閱讀