📄 6.4.txt
字号:
Listing 6.4 Creating a Custom Exception Class
using System;
using System.Collections;
namespace _4_CustomException
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
OddIntCollection oddValues = new OddIntCollection();
int input = 0;
do
{
// get input from user
Console.Write( “Enter an odd number or -1 to quit: “ );
input = Int32.Parse( Console.ReadLine() );
// add it to the collection
if( input != -1 )
oddValues.Add( input );
} while( input != -1 );
}
}
class OddIntCollection : CollectionBase
{
public void Add( int value )
{
// check if value is odd by using a logical & on first bit
if( (value & 0x1) == 0 )
{
// value isn’t odd, throw the custom exception
throw new OddIntException();
}
else
{
// add value to inner collection
InnerList.Add( value );
}
}
}
class OddIntException : ApplicationException
{
// override Message property to display custom message
public override string Message
{
get
{
return “Value is not an odd number”;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -