參照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( ) );
}
}
}運行結果為: