Exception Handling in C# – Part I

Introduction

Exception handling is handling known or unknown errors from the program. So, when any error occurs then the program should recover gracefully from the error.

In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing – during the execution of a program.

Wiki

The basic purpose of exception handling is to maintain the normal flow of the program irrespective of errors or exceptions which might occur during the execution of the program.

Error categories

In programming error are categorized in two types:

Compile Time Errors

These errors are those which occur due to syntactical errors like not putting a semi-colon at the end of the statement or missing a curly brace while starting or ending a code block. But such errors are caught by the IDE itself and the programmer is notified about such errors. The code does not run till the time such errors are rectified.

Run-Time Errors

Run time errors are those errors that occur not at the compile-time, but they occur at the runtime. Run-Time Errors are called Exceptions. Hence, we only need to handle the exceptions as Compile-time errors can be handled by IDE itself.

Why exception occurre

There is various reasons for exceptions occurrence

Wrong logic implementation

CLR (Common Language Runtime) cannot check the logic at compile time, it simply checks for the syntax at compile time which everyone should follow.

For example, let’s look at the following code, which is attempting to add up the numbers one to hundred:

using System;

namespace ExceptionExample
{
    public class Program    
    {
        public static void Main()
        {
            var start = 100;
            var end = 1;
            var result = 0;

            for (int i = start; i < end; i++)
            {
                result++;
            }

            Console.WriteLine($"Result: {result}");
            Console.ReadLine();
        }
    }
}

When the code is run, however, it gives an answer of zero. The programme runs OK and didn’t produce any error message or wavy lines. It’s just not the correct answer!

The problem is that we’ve made an error in our logic. The start variable should be 1 and the end variable 100. We’ve got it the other way around, in the code. So, the loop never executes.

Wrong Inputs to run the program

suppose the application requires the user to enter an integer value, however the value supplied is anything but integer. Hence in such a case also the program will terminate abruptly. Consider the following example:

Code for Program class:

using System;

namespace ExceptionExample
{
    public class Program    
    {
        public static void Main()
        {
            Console.WriteLine("Enter a number:");
            var n = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter a number:");
            var n1 = Convert.ToInt32(Console.ReadLine());

            var result = n / n1;

            Console.WriteLine($"Result: {result}");
            Console.ReadLine();
        }
    }
}

Now in this program if you enter an integer value the program will run smoothly. But if you provide a string value, you will encounter a “FormatException”.

Connectivity issues

suppose you have written a program to connect to the database and access database information but for some reason database server is offline. Now if you run the program, it will error out as the connection issue.

These are some of the typical runtime errors there are several reasons why runtime errors occur and to run the smooth program we need to handle this run time exceptions.

If you do not handle those exception, then the program can be abruptly terminating on the line where such an error occurs, and remaining line of code will not be executed.

Next post will explain about how to implement exception , nested try-catch blocks and creating custom exception’s

List of exception

Here is complete the list of Exceptions:

Sr.No.Exception Class & Description
1AccessViolationException

It is thrown when try to read or write protected memory.
2AggregateException

Represents one or more errors that occur during application execution.
3AppDomainUnloadedException

It is thrown when try to access an unloaded application domain.
4ApplicationException

It is base class for application-defined exceptions.
5ArgumentException

It is thrown when invalid argument provided to a method.
6ArgumentNullException

It is thrown when a method requires argument but no argument is provided.
7ArgumentOutOfRangeException

It is thrown when value of an argument is outside the allowable range.
8ArithmeticException

It is thrown when doing arithmetic, casting, or conversion operation.
9ArrayTypeMismatchException

It is thrown when try to store an element of the wrong type within an array.
10BadImageFormatException

It is thrown when file image, dll or exe program is invalid.
11CannotUnloadAppDomainException

It is thrown when try to unload an application domain fails.
12ContextMarshalException

The exception that is thrown when an attempt to marshal an object across a context boundary fails.
13DataMisalignedException

It is thrown thrown when a unit of data is read from or written to an address that is not a multiple of the data size.
14DivideByZeroException

It is thrown when there is an attempt to divide an integral or decimal value by zero.
15DllNotFoundException

It is thrown when a DLL specified in a DLL import cannot be found.
16DuplicateWaitObjectException

The exception that is thrown when an object appears more than once in an array of synchronization objects.
17EntryPointNotFoundException

The exception that is thrown when an attempt to load a class fails due to the absence of an entry method.
18ExecutionEngineException

The exception that is thrown when there is an internal error in the execution engine of the common language runtime.
19FieldAccessException

It is thrown when there is an invalid attempt to access a private or protected field inside a class.
20FormatException

The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed.
21IndexOutOfRangeException

The exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds.
22InsufficientMemoryException

The exception that is thrown when a check for sufficient available memory fails. This class cannot be inherited.
23InvalidCastException

The exception that is thrown for invalid casting or explicit conversion.
24InvalidOperationException

The exception that is thrown when a method call is invalid for the object’s current state.
25InvalidProgramException

The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata.
26InvalidTimeZoneException

The exception that is thrown when time zone information is invalid.
27MemberAccessException

The exception that is thrown when an attempt to access a class member fails.
28MethodAccessException

The exception that is thrown when there is an invalid attempt to access a method, such as accessing a private method from partially trusted code.
29MissingFieldException

The exception that is thrown when there is an attempt to dynamically access a field that does not exist.
30MissingMemberException

The exception that is thrown when there is an attempt to dynamically access a class member that does not exist.
31MissingMethodException

The exception that is thrown when there is an attempt to dynamically access a method that does not exist.
32MulticastNotSupportedException

The exception that is thrown when there is an attempt to combine two delegates based on the Delegate type instead of the MulticastDelegate type.
33NotCancelableException

It is thrown when an attempt is made to cancel an operation that is not cancelable.
34NotFiniteNumberException

The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Not-a-Number (NaN).
35NotImplementedException

The exception that is thrown when a requested method or operation is not implemented.
36NotSupportedException

The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
37NullReferenceException

The exception that is thrown when there is an attempt to dereference a null object reference.
38ObjectDisposedException

The exception that is thrown when an operation is performed on a disposed object.
39OperationCanceledException

The exception that is thrown in a thread upon cancellation of an operation that the thread was executing.
40OutOfMemoryException

The exception that is thrown when there is not enough memory to continue the execution of a program.
41OverflowException

The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow.
42PlatformNotSupportedException

The exception that is thrown when a feature does not run on a particular platform.
43RankException

The exception that is thrown when an array with the wrong number of dimensions is passed to a method.
44StackOverflowException

The exception that is thrown when the execution stack overflows because it contains too many nested method calls.
45SystemException

Serves as the base class for system exceptions namespace.
46TimeoutException

The exception that is thrown when the time allotted for a process or operation has expired.
47TimeZoneNotFoundException

The exception that is thrown when a time zone cannot be found.
48TypeAccessException

The exception that is thrown when a method attempts to use a type that it does not have access to.
49TypeInitializationException

The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.
50TypeLoadException

The exception that is thrown when type-loading failures occur.
51TypeUnloadedException

The exception that is thrown when there is an attempt to access an unloaded class.
52UnauthorizedAccessException

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.
53UriFormatException

The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected.
54ConstraintException

Represents the exception that is thrown when attempting an action that violates a constraint.
55DataException

Represents the exception that is thrown when attempting an action that violates a constraint.
56DBConcurrencyException

Gets or sets the value of the DataRow that generated the DBConcurrencyException.
57DeleteRowInaccessibleException

Represents the exception that is thrown when an action is tried on a DataRow that has been deleted.
58DuplicateNameException

Represents the exception that is thrown when a duplicate database object name is encountered during an add operation in a DataSet -related object.
59EvaluateException

Represents the exception that is thrown when the Expression property of a DataColumn cannot be evaluated.
60InRowChangingEventException

Represents the exception that is thrown when you call the EndEdit method within the RowChanging event.
61InvalidConstraintException

Represents the exception that is thrown when incorrectly trying to create or access a relation.
62InvalidExpressionException

Represents the exception that is thrown when you try to add a DataColumn that contains an invalid Expression to a DataColumnCollection.
63MissingPrimaryKeyException

Represents the exception that is thrown when you try to access a row in a table that has no primary key.
64NoNullAllowedException

Represents the exception that is thrown when you try to insert a null value into a column where AllowDBNull is set tofalse.
65OperationAbortedException

This exception is thrown when an ongoing operation is aborted by the user.
66ReadOnlyException

Represents the exception that is thrown when you try to change the value of a read-only column.
67RowNotInTableException

Represents the exception that is thrown when you try to perform an operation on a DataRow that is not in a DataTable.
68StrongTypingException

The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value.
69SyntaxErrorException

Represents the exception that is thrown when the Expression property of a DataColumn contains a syntax error.
70TypedDataSetGeneratorException

The exception that is thrown when a name conflict occurs while generating a strongly typed DataSet.
71VersionNotFoundException

Represents the exception that is thrown when you try to return a version of a DataRow that has been deleted.
72DirectoryNotFoundException

The exception that is thrown when part of a file or directory cannot be found.
73DriveNotFoundException

The exception that is thrown when a drive that is referenced by an operation could not be found.
74EndOfStreamException

An EndOfStreamException exception is thrown when there is an attempt to read past the end of a stream.
75FileFormatException

The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed.
76FileLoadException

The exception that is thrown when a managed assembly is found but cannot be loaded.
77FileNotFoundException

The exception that is thrown when an attempt to access a file that does not exist on disk fails.
78InternalBufferOverflowException

The exception thrown when the internal buffer overflows.
79InvalidDataException

The exception that is thrown when a data stream is in an invalid format.
80IOException

The exception that is thrown when an I/O error occurs.
81PathTooLongException

The exception that is thrown when a path or file name is longer than the system-defined maximum length.
82PipeException

Thrown when an error occurs within a named pipe.
Exception Table

In the next post Exception Handling C# – Part II, will cover the way to handle the exception, multiple exception handling, and writing custom exception.

Leave a Reply

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