Programming in C# – Exception Handling

Handle Exceptions

  • We need to handle an exception to stop the system from running
  • Finally block will run at the end
  • Environment.FailFast() will mean that the finally block will not run. It will also not run if there is a power outage.

System.Exception properties

StackTrace

A string that describes all the methods that are currently in execution. This gives you a way of tracking which method threw the exception and how that method was reached.

InnerException

When a new exception is thrown because another exception happened, the two are linked together with the InnerException property.

Message

A (hopefully) human friendly message that describes the exception.

HelpLink

A Uniform Resource Name (URN) or uniform resource locater (URL) that points to a help file.

HResult

A 32-bit value that describes the severity of an error, the area in which the exception happened and a unique number for the exception This value is used only when crossing managed and native boundaries.

Source

The name of the application that caused the error. If the Source is not explicitly set, the name of the assembly is used.

TargetSite

Contains the name of the method that caused the exception. If this data is not available, the property will be null.

Data

A dictionary of key/value pairs that you can use to store extra data for your exception. This data can be read by other catch blocks and can be used to control the processing of the exception.

Runtime Exceptions

 

 

 

ArithmeticException: A base class for other exceptions that occur during arithmetic

operations.

ArrayTypeMismatchException: Thrown when you want to store an incompatible element inside an array.

DivideByZeroException: Thrown when you try to divide a value by zero.

IndexOutOfRangeException: Thrown when you try to access an array with an index

that’s less than zero or greater than the size of the array.

InvalidCastException: Thrown when you try to cast an element to an incompatible

type.

NullReferenceException: Thrown when you try to reference an element that’s null.

OutOfMemoryException: Thrown when creating a new object fails because the CLR

doesn’t have enough memory available.

OverflowException: Thrown when an arithmetic operation overflows in a

checked context.

StackOverflowException:

Thrown when the execution stack is full. This can happen in a recursive operation that doesn’t exit.

TypeInitializationException:

Thrown when a static constructor throws an

Name

Description

Exception

The base class for all exceptions. Try avoiding throwing and catching this exception because it’s too generic.

ArgumentException

Throw this exception when an argument to your method is invalid.

ArgumentNullException

A specialized form of ArgumentException that you can throw when one of your arguments is null and this isn’t allowed.

ArgumentOutOfRangeException

A specialized form of ArgumentException that you can throw when an argument is outside the allowable range of values.

FormatException

Throw this exception when an argument does not have a valid format.

InvalidOperationException

Throw this exception when a method is called that’s invalid for the object’s current state.

NotImplementedException

This exception is often used in generated code where a method has not been implemented yet.

NotSupportedException

Throw this exception when a method is invoked that you don’t support.

ObjectDisposedException

Throw when a user of your class tries to access methods when Dispose has already been called.

Creating Custom Exceptions

Below is an example of a custom exception

[Serializable]

public class OrderProcessingException : Exception, ISerializable

{

public OrderProcessingException(int orderId)

{

OrderId = orderId;

this.HelpLink = “http://www.mydomain.com/infoaboutexception”;

}

public OrderProcessingException(int orderId, string message)

: base(message)

{

OrderId = orderId;

this.HelpLink = “http://www.mydomain.com/infoaboutexception”;

}

public OrderProcessingException(int orderId, string message,

Exception innerException)

: base(message, innerException)

{

OrderId = orderId;

this.HelpLink = “http://www.mydomain.com/infoaboutexception”;

}

protected OrderProcessingException(SerializationInfo info, StreamingContext context)

{

OrderId = (int)info.GetValue(“OrderId”, typeof(int));

}

public int OrderId { get; private set; }

public void GetObjectData(SerializationInfo info, StreamingContext context)

{

info.AddValue(“OrderId”, OrderId, typeof(int));

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *