Learning Objectives
After completing the session, you will be able to: Explain Exception handling in C#
Exception handling in C#
C# handles errors and abnormal conditions with exceptions. An exception is an object that encapsulates information about an unusual program occurrence, such as running out of memory or losing a network connection. When an exceptional circumstance arises, an exception is thrown. You might decide to throw an exception in our methods (for example, if you find an invalid
parameter has been provided), these popularly known as Application exceptions.
You provide for the possibility of exceptions by adding try/catch blocks in the program. The catch blocks are also called exception handlers. The idea is that we try potentially dangerous code, and if an exception is thrown we catch the exception in the catch block and handle the situation appropriately. Ideally, after the exception is caught the program can fix the problem and continue or you can print a meaningful error message and terminate gracefully.
try
{ // Code where we are anticipating the Exception }
catch (Exception) { //Do Nothing
// Just Eat Away the Exception }
When a program encounters an exceptional circumstance, such as running out of memory, it throws (or raises) an exception. The runtime will search for an appropriate exception handler, like in the following example, if the file is not found and hence FileNotFound Exception will be thrown and it will be handled by the FileNotFoundException catch block, if there was any other IO related exception, it will be handled by the IOException catch block and if there was some other exception it will be handled by the generic Exception catch block.
try
{ //trying to access a secured file } catch(FileNotFoundException e1) { //handle FileNotFoundException } catch(IOException e2) { //handle IOException
}
catch(Exception e3)
{ //handle generic exception }
The order of the catch block is very important, if for example the same catch block was arranged as follows, even if there was a FileNotFoundException, it will be handled by generic IO exception catch block as it is placed in front of the FileNotFoundException handling block.
try
{ //trying to access a secured file } catch(IOException e1) { //handle IOException } catch(FileNotFoundException e2) { //handle FileNotFoundException } catch(Exception e3)
{ //handle generic exception }
The search for an exception handler will also unwind the stack i.e. if the currently running function does not handle the exception, the current function terminates and the calling function gets a chance to handle the exception. If none of the calling functions handles it, the exception ultimately is handled by the Common Language Runtime (CLR), which abruptly terminates the program. private void Method()
{
try
{ //Invoke MethodA
MethodA(); }
catch( SecurityException ex) {
// handle gracefully the access denied scenario }
}
private void MethodB()
{ //Invoke MethodA
MethodB(); }
private void MethodB()
{ //trying to access a secured file
//An exception here will bubble up the stack to Method() }
Throw Statement
To signal an abnormal condition in a C# program, throw an exception by using the throw keyword. The following line of code creates a new instance of System.Exception and then throws it, similary you can also throw any specific exceptions.
throw new Exception(“There is an unhandled situation”);
Finally Statement
In some instances, throwing an exception and unwinding the stack can create a problem. For example, if you opened, you might need an opportunity to close the file or flush the buffer.
If there is some action that must be made regardless of whether an exception is thrown, such as closing a file. One approach is to enclose the dangerous action in a try block and then to perform the necessary action (close the file) in both the catch and try blocks. However, this is an ugly duplication of code, and its error prone. C# provides a better alternative in the finally block.
You create a finally block with the keyword finally, and enclose the block in braces. The code in the finally block is guaranteed to be executed regardless of whether an exception is thrown.
private void Create Customer() { try
{ // open a db connection and perform some operation }
catch(Exception e)
{ //log and clean-up code }
finally {
//close the db connection }
}
A finally block can be created with or without catch blocks, but a finally block requires a try block to execute. In the following scenario, the finally block will get executed before the exception is handled somewhere higher in the stack call.
private void CreateCustomer() { try
{ // open a db connection and perform some operation }
finally
{ //close the db connection }
User Defined Exceptions
C# allows creating user defined exception class and this class should be derived from Exception base class. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.
Using System;
class UserDefinedException : Exception {
Public MyException( string str) {
Console.WriteLine("User defined exception"); }
}
Exception Type
There are two types of exceptions: Application Exception System Exception
Application Exception
User applications, not the common language runtime, throw custom exceptions derived from the Application Exception class. The Application Exception class differentiates between exceptions defined by applications versus exceptions defined by the system.
If you are designing an application that needs to create its own exceptions, then you are advised to derive custom exceptions from the Exception class. It was originally thought that custom
exceptions should derive from the Application Exception class; however in practice this has not been found to add significant value
Public Constructors:
S.No Name Description
1 ExceptionCollection Initializes a new instance of the ExceptionCollection class.
Public Properties:
S.No Name Description
1 Data Gets a collection of key/value pairs that provide additional, user- defined information about the exception.(Inherited from Exception.) 2 Exceptions Gets the array of Exception objects that represent the collection of
exceptions.
3 HelpLink Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)
4 InnerException Gets the Exception instance that caused the current exception.(Inherited from Exception.)
S.No Name Description
5 Message Gets a message that describes the current exception.(Inherited from Exception.)
6 Source Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)
7 StackTrace Gets a string representation of the frames on the call stack at the time the current exception was thrown.(Inherited from Exception.) 8 TargetSite Gets the method that throws the current exception.(Inherited from
Exception.)
Protected Properties
S.No Name Description
1 HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public Methods
S.No Name Description
1 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)
2 GetBaseException When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
3 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
4 GetObjectData Overridden. Populates a SerializationInfo with the data needed to serialize the ExceptionCollection.
5 GetType Gets the runtime type of the current instance. (Inherited from Exception.)
6 Reference Equals Determines whether the specified Object instances are the same instance. (Inherited from Object.)
7 ToString Creates and returns a string representation of the current exception. (Inherited from Exception.)
Protected Methods:
S.No Name Description
1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
2 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
System Exception
Represents errors that occur during application execution. This is the base class for all exceptions. The following table describes some of the system exceptions:
Summary
Overview of Exceptions: C# provides three keywords try, catch and finally to do exception handling.
Exception Class: The System.Exception Class is small class representing information about the kind of Exception.
Exception Class Properties are Message, source, stacktrace, targetsite, helplink, InnerException
Exception Hierarchy:
o SystemExceptions: The CLR generates SystemExceptions, which can occur at any point during program execution
o ApplicationException: It is a base class that programmers can extend to create exception classes that are specific to their applications
Test your Understanding
1. What do you understand by Exception class? 2. State some features about Exception properties.
3. Differentiate between System Exceptions and User defined Exceptions. 4. Describe some system exceptions.