Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 8 - Back to Basics: Exceptions<br />
� public YourException()<br />
� public YourException(string message)<br />
� public YourException(string message, Exception innerException)<br />
� protected YourException(SerializationInfo info, StreamingContext context)<br />
The first three allow your exception to be used in an expected manner. The fourth is used to support<br />
serialization incase .NET needs to serialize your exception - which means you should also implement the<br />
GetObjectData method. The purpose <strong>of</strong> support serialization is in the case where you have custom<br />
properties, which you'd like to have survive being serialized/deserialized. Here's the complete example:<br />
[Serializable]<br />
public class UpgradeException: Exception<br />
{<br />
private int _upgradeId;<br />
}<br />
public int UpgradeId { get { return _upgradeId; } }<br />
public UpgradeException(int upgradeId)<br />
{<br />
_upgradeId = upgradeId;<br />
}<br />
public UpgradeException(int upgradeId, string message, Exception inner)<br />
: base(message, inner)<br />
{<br />
_upgradeId = upgradeId;<br />
}<br />
public UpgradeException(int upgradeId, string message) : base(message)<br />
{<br />
_upgradeId = upgradeId;<br />
}<br />
protected UpgradeException(SerializationInfo info, StreamingContext c)<br />
: base(info, c)<br />
{<br />
if (info != null)<br />
{<br />
_upgradeId = info.GetInt32("upgradeId");<br />
}<br />
}<br />
public override void GetObjectData(SerializationInfo i, StreamingContext c)<br />
{<br />
if (i != null)<br />
{<br />
i.AddValue("upgradeId", _upgradeId);<br />
}<br />
base.GetObjectData(i, c)<br />
}<br />
<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />
71