C#.NET中的定製異常(Exception)

來源:互聯網
上載者:User
參照MSDN的異常定製/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-17
 * Time: 18:18
 * 
 * 定製異常
 */

using System;

    class NotEvenException : Exception//定製的異常要繼承自System.Exception類
    {
        const string str1 = "函數所需的參數是偶數。";

        public NotEvenException() :
            base( str1 )//不帶參數的建構函式,繼承自基類的建構函式
        { }

        public NotEvenException( string str2 ) :
            base( String.Format( "{0} - {1}",str2, str1 ) )//帶參數的建構函式,繼承自基類的建構函式
        { }
    }

    class NewSExceptionDemo 
    {
        public static void Main() 
        {
            Console.WriteLine ("\n現在,一個異常通過基類的建構函式被拋出\n");
            CalcHalf( 18 );
            CalcHalf( 21 );

            Console.WriteLine ("\n現在,一個異常通過衍生類別的建構函式被拋出\n");
            CalcHalf2( 30 );
            CalcHalf2( 33 );
        }
        
        //如果input參數不是偶數,Half函數就跑出一個基類異常
        static int Half( int input )
        {
            if( input % 2 != 0 )
                throw new Exception( String.Format("參數 {0} 不能被2整除。", input ) );

            else return input / 2;
        }

        //如果input參數不是偶數,Half2函數就跑出一個衍生類別異常
        static int Half2( int input )
        {
            if( input % 2 != 0 )
                throw new NotEvenException( 
                    String.Format( "無效參數:{0}", input ) );

            else return input / 2;
        }

        // CalcHalf方法調用Half方法,並捕捉任何拋出的異常
        static void CalcHalf(int input )
        {
            try
            {
                int halfInput = Half( input );
                Console.WriteLine( 
                    "{0}的一半為{1}.", input, halfInput );
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }

        // CalcHalf2方法調用Half2方法,並捕捉任何拋出的異常
        static void CalcHalf2(int input )
        {
            try
            {
                int halfInput = Half2( input );
                Console.WriteLine( 
                    "{0}的一半是{1}.", input, halfInput );
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }
    }運行結果為:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.