在工作中,有时需要在抛出的异常中带入错误代码,此时就需要使用自定义异常来实现。
自定义异常如下:
[Serializable]
internal class HoundException : Exception
{
public HoundException()
{
}
public HoundException(int nErrorCode, string message) : base(message)
{
ErrorCode = nErrorCode;
}
public HoundException(int nErrorCode, string message, Exception innerException) : base(message, innerException)
{
ErrorCode = nErrorCode;
}
protected HoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public int ErrorCode { get; private set; }
}
使用:
private void TestFunc()
{
throw new HoundException(10001, "TestFunc failed.");
}
异常的捕获:
catch (HoundException ex)
{
LogFile.ErrorFormat("Exception {0} - {1}", ex.ErrorCode, ex.Message);
}
输出:
Exception 10001 - TestFunc failed.