C#異常處理 try、catch、finally

1.當除以0,拋出異常
namespace ClassTest
{
    class Program
    {
        int result;
        Program()
        {
            result=0;
        }
        public void division(int num1,int num2)
        {
            try{
                result=num1/num2;
            }
            catch(DivideByZeroException e)
            {
                Console.WriteLine("Exception caught:{0}",e);
            }
            finally{
                Console.WriteLine("Result:{0}",result);
            }
        }
        static void Main(string[] args)  //主函數
        {
            Program d = new Program();
            d.division(25,0);
            Console.ReadKey();
        }
    }
}

2.創建用戶自定義異常

 用戶自定義的異常類是派生自 ApplicationException 類

namespace ClassTest
{
    class Program
    {
        static void Main(string[] args)  //主函數
        {
            Temp temp = new Temp();
            try
            {
                temp.showTemp();
            }
            catch (IsZeroException e)
            {
                Console.WriteLine("IsZeroException:{0}",e.Message);
            }
            Console.ReadKey();
        }
    }
}
public class IsZeroException : ApplicationException
{
    public IsZeroException(string message) : base(message) { }
}
public class Temp
{
    int temp = 0;
    public void showTemp()
    {
        if (temp == 0)
            throw (new IsZeroException("Zero temperature found."));
        else
            Console.WriteLine("Temperature:{0}",temp);
    }
}

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