Contents
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 |
1 | AccessViolationException It is thrown when try to read or write protected memory. |
2 | AggregateException Represents one or more errors that occur during application execution. |
3 | AppDomainUnloadedException It is thrown when try to access an unloaded application domain. |
4 | ApplicationException It is base class for application-defined exceptions. |
5 | ArgumentException It is thrown when invalid argument provided to a method. |
6 | ArgumentNullException It is thrown when a method requires argument but no argument is provided. |
7 | ArgumentOutOfRangeException It is thrown when value of an argument is outside the allowable range. |
8 | ArithmeticException It is thrown when doing arithmetic, casting, or conversion operation. |
9 | ArrayTypeMismatchException It is thrown when try to store an element of the wrong type within an array. |
10 | BadImageFormatException It is thrown when file image, dll or exe program is invalid. |
11 | CannotUnloadAppDomainException It is thrown when try to unload an application domain fails. |
12 | ContextMarshalException The exception that is thrown when an attempt to marshal an object across a context boundary fails. |
13 | DataMisalignedException 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. |
14 | DivideByZeroException It is thrown when there is an attempt to divide an integral or decimal value by zero. |
15 | DllNotFoundException It is thrown when a DLL specified in a DLL import cannot be found. |
16 | DuplicateWaitObjectException The exception that is thrown when an object appears more than once in an array of synchronization objects. |
17 | EntryPointNotFoundException The exception that is thrown when an attempt to load a class fails due to the absence of an entry method. |
18 | ExecutionEngineException The exception that is thrown when there is an internal error in the execution engine of the common language runtime. |
19 | FieldAccessException It is thrown when there is an invalid attempt to access a private or protected field inside a class. |
20 | FormatException The exception that is thrown when the format of an argument is invalid, or when a composite format string is not well formed. |
21 | IndexOutOfRangeException 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. |
22 | InsufficientMemoryException The exception that is thrown when a check for sufficient available memory fails. This class cannot be inherited. |
23 | InvalidCastException The exception that is thrown for invalid casting or explicit conversion. |
24 | InvalidOperationException The exception that is thrown when a method call is invalid for the object’s current state. |
25 | InvalidProgramException The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. |
26 | InvalidTimeZoneException The exception that is thrown when time zone information is invalid. |
27 | MemberAccessException The exception that is thrown when an attempt to access a class member fails. |
28 | MethodAccessException 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. |
29 | MissingFieldException The exception that is thrown when there is an attempt to dynamically access a field that does not exist. |
30 | MissingMemberException The exception that is thrown when there is an attempt to dynamically access a class member that does not exist. |
31 | MissingMethodException The exception that is thrown when there is an attempt to dynamically access a method that does not exist. |
32 | MulticastNotSupportedException The exception that is thrown when there is an attempt to combine two delegates based on the Delegate type instead of the MulticastDelegate type. |
33 | NotCancelableException It is thrown when an attempt is made to cancel an operation that is not cancelable. |
34 | NotFiniteNumberException The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Not-a-Number (NaN). |
35 | NotImplementedException The exception that is thrown when a requested method or operation is not implemented. |
36 | NotSupportedException 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. |
37 | NullReferenceException The exception that is thrown when there is an attempt to dereference a null object reference. |
38 | ObjectDisposedException The exception that is thrown when an operation is performed on a disposed object. |
39 | OperationCanceledException The exception that is thrown in a thread upon cancellation of an operation that the thread was executing. |
40 | OutOfMemoryException The exception that is thrown when there is not enough memory to continue the execution of a program. |
41 | OverflowException The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow. |
42 | PlatformNotSupportedException The exception that is thrown when a feature does not run on a particular platform. |
43 | RankException The exception that is thrown when an array with the wrong number of dimensions is passed to a method. |
44 | StackOverflowException The exception that is thrown when the execution stack overflows because it contains too many nested method calls. |
45 | SystemException Serves as the base class for system exceptions namespace. |
46 | TimeoutException The exception that is thrown when the time allotted for a process or operation has expired. |
47 | TimeZoneNotFoundException The exception that is thrown when a time zone cannot be found. |
48 | TypeAccessException The exception that is thrown when a method attempts to use a type that it does not have access to. |
49 | TypeInitializationException The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited. |
50 | TypeLoadException The exception that is thrown when type-loading failures occur. |
51 | TypeUnloadedException The exception that is thrown when there is an attempt to access an unloaded class. |
52 | UnauthorizedAccessException The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error. |
53 | UriFormatException The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected. |
54 | ConstraintException Represents the exception that is thrown when attempting an action that violates a constraint. |
55 | DataException Represents the exception that is thrown when attempting an action that violates a constraint. |
56 | DBConcurrencyException Gets or sets the value of the DataRow that generated the DBConcurrencyException. |
57 | DeleteRowInaccessibleException Represents the exception that is thrown when an action is tried on a DataRow that has been deleted. |
58 | DuplicateNameException Represents the exception that is thrown when a duplicate database object name is encountered during an add operation in a DataSet -related object. |
59 | EvaluateException Represents the exception that is thrown when the Expression property of a DataColumn cannot be evaluated. |
60 | InRowChangingEventException Represents the exception that is thrown when you call the EndEdit method within the RowChanging event. |
61 | InvalidConstraintException Represents the exception that is thrown when incorrectly trying to create or access a relation. |
62 | InvalidExpressionException Represents the exception that is thrown when you try to add a DataColumn that contains an invalid Expression to a DataColumnCollection. |
63 | MissingPrimaryKeyException Represents the exception that is thrown when you try to access a row in a table that has no primary key. |
64 | NoNullAllowedException Represents the exception that is thrown when you try to insert a null value into a column where AllowDBNull is set tofalse. |
65 | OperationAbortedException This exception is thrown when an ongoing operation is aborted by the user. |
66 | ReadOnlyException Represents the exception that is thrown when you try to change the value of a read-only column. |
67 | RowNotInTableException Represents the exception that is thrown when you try to perform an operation on a DataRow that is not in a DataTable. |
68 | StrongTypingException The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value. |
69 | SyntaxErrorException Represents the exception that is thrown when the Expression property of a DataColumn contains a syntax error. |
70 | TypedDataSetGeneratorException The exception that is thrown when a name conflict occurs while generating a strongly typed DataSet. |
71 | VersionNotFoundException Represents the exception that is thrown when you try to return a version of a DataRow that has been deleted. |
72 | DirectoryNotFoundException The exception that is thrown when part of a file or directory cannot be found. |
73 | DriveNotFoundException The exception that is thrown when a drive that is referenced by an operation could not be found. |
74 | EndOfStreamException An EndOfStreamException exception is thrown when there is an attempt to read past the end of a stream. |
75 | FileFormatException 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. |
76 | FileLoadException The exception that is thrown when a managed assembly is found but cannot be loaded. |
77 | FileNotFoundException The exception that is thrown when an attempt to access a file that does not exist on disk fails. |
78 | InternalBufferOverflowException The exception thrown when the internal buffer overflows. |
79 | InvalidDataException The exception that is thrown when a data stream is in an invalid format. |
80 | IOException The exception that is thrown when an I/O error occurs. |
81 | PathTooLongException The exception that is thrown when a path or file name is longer than the system-defined maximum length. |
82 | PipeException Thrown when an error occurs within a named pipe. |
In the next post Exception Handling C# – Part II, will cover the way to handle the exception, multiple exception handling, and writing custom exception.