这段代码运行良好,但如果我想在其他程序中使用它,我该怎么做呢?
是否可以像类库一样创建异常?如果是,如何?
namespace Exception_CreatingUserDefined
{
public class FirstOperandSmallException : Exception
{
public FirstOperandSmallException(String message) : base (message)
{
}
}
public class operation
{
int op1, op2;
public void operatn()
{
if(op1 < op2)
{
throw (new FirstOperandSmallException("First Operand Should not be Small"));
}
else {
//Do nothing
}
}
}
class Test
{
static void Main(string[] args)
{
operation opr = new operation();
try
{
opr.operatn();
}
catch(FirstOperandSmallException e)
{
Console.WriteLine("FirstOperandSmallException : {0}",e.Message);
}
Console.Read();
}
}
}
请您参考如下方法:
正如 Kenny 所说,只需包含您的命名空间,您就可以使用您在其中定义的任何公共(public)类。为此,请执行以下操作:
- 公开您的异常类(和所需的构造函数)。
- 将此程序集的输出类型更改为“库”类型。为此,请右键单击您的项目并转到“属性”并将输出类型设置为“库”。
此外,类库的常见做法是删除您的main(入口)代码,因此它只有类和方法。
