Exceptions

 This is one of the major features of OOP languages like C++, VC++, VB.NET, C#.NET, Java etc.
 Def: "The process of handling the run time exceptions" is called as "Exception handling".
Note: Exception = Run time error
Types of Errors:
1) Compile Time Errors: The errors occurred after compiling the program are called as “compile time errors”.
2) Run Time Errors: The errors occurred during the execution of the program is called as “run time errors”.

Overview of Exception Handling:
 The exception may occur at run time, based on the mistake of the user / programmer / system problem also.
 When exception is raised, automatically it leads to "abnormal application termination".
 The cause of the exception may be anything; the project developer should take care about the exceptions.
 As a part of this exception handling, the programmer has to display "particular error message" to the user.
 The major purpose of Exception Handling is to avoid "abnormal application termination".

Types of Application Termination:
 Normal Application Termination: Whenever the program execution controls executes all the statements in the program and reaches to end of the code, the application will be terminated automatically. It can be called as “Normal Application Termination”.
 Abnormal Application Termination: Whenever an exception occurred at run time, the application will be terminated automatically. It can be called as “Abnormal Application Termination”.

Simple Demo on Exceptions using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo1
{
class Program
{
static void Main(string[] args)
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
Console.Read();
}
}
}
In the above code, the highlighted line contains an error, because it is trying to access an array element which is in out of range of the array. So, it leads to abnormal application termination at run time. To avoid this, we have to implement exception handling for this code.

Syntax of Exception Handling:

try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}

In the above syntax, we can observe to blocks.
1) try block
2) catch block
1) try block:
• The try block contains the actual code, which is to be executed.
• After every try block, there should catch block without fail.
• The system tries to execute the code in the try block.
• During the execution, if any exception occurs, then the execution control automatically goes to catch block.
• At the same time, the “try” block throws the exception to the catch block in the form of an object. That object is called as “exception object”.

try
{
---------------------;
---------------------;
---------------------;
---------------------;
}

2) catch block:
• This is also known as “error handler”.
• This is followed by the try block.
• The catch block will be executed if any exception is occurred during the execution of try block.
• The catch block contains necessary code which displays an error message to the user.
• This receives the exception, thrown by the try block, in the form of an object. In the following syntax, “ex” is the “Exception object”. The “Exception” is the class of the exception object.

catch (Exception ex)
{
--------------------;
--------------------;
}

Exception Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionDemo2
{
class Program
{
static void Main(string[] args)
{
try
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred.");
}
Console.Read();
}
}
}
Exceptions

Types of Catch Block Messages:

Already we have discussed that the catch block generates an error message, when an exception occurs. That error message can be of two types.
1. User Defined Message
2. System Defined Message

1. User Defined Message: Your own message can be written.
Ex: “Error Occurred.”
“Operation is not successful”.
etc.

2. System Defined Message: The system provides the description of the error, so that you can print that on the output directly. To access the system defined message, you can use the exception object as follows:
Syn: ex.Message

catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Exceptional Classes

 Already you know that C# recognizes the exception as an object.
 To declare the exception object, we are using a class called “System.Exception”, in the previous examples.
 The “System.Exception” class recognizes any type of exceptions. In order to catch the particular type of error, C# provides other exceptional classes. Some of them are given here.
1 System.OverflowException Occurs when a large value is assigned to a variable, which is not fit in that variable.
2 System.FormatException / System.InvalidCastException Occurs when the casting is failed from one data type of another data type.
3 System.DivideByZeroException Occurs when any number is divided by 0.
4 System.IndexOutOfRangeException Occurs when an index is accessed in out of range.
5 System.InsufficientMemoryException Occurs when there is no sufficient memory in RAM for the execution of the application.
6 System.IO.FileNotFoundException Occurs when a non-existing file is accessed.
7 System.IO.DirectoryNotFoundException Occurs when a non-existing directory is accessed.
8 System.IO.FileLoadException Occurs when any error occurred during the opening of any file.
9 System.IO.IOException Occurs when any error occurred during file read or writing.
10 System.Threading.ThreadInterruptedException Occurs when any error occurred during the execution of the thread.
11 System.Threading.ThreadStartException Occurs when any error occurred while starting the thread.
12 System.InvalidOperationException Occurs when any error occurred while opening the database connection.
13 System.Data.OleDb.OleDbException Occurs when any error occurred while performing query or non-query transactions on OleDb databases.
14 System.Data.SqlClient.SqlException Occurs when any error occurred while performing query or non-query transactions on SqlServer database.
15 System.EntryPointNotFoundException Occurs when you try to run the application, without defining any entry point (main() method).
16 System.InvalidTimeZoneException Occurs when the system has an invalid time zone setting the date & time settings.
Note: Based on the situation, the above specified exception classes could be used.

Exceptional Classes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo3
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;
Console.WriteLine("Enter first value:");
n1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());
n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
Console.Read();
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Can't divide the number with zero.");
}
Console.Read();
}
}
}
Exceptions
Note: If you want to handle more than one type of exception for the same try block, then you need to write multiple catch blocks.

Multiple Catch Blocks

Note: If you want to handle more than one type of exception for the same try block, then you need to write multiple catch blocks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo4
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");
n1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());
n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
Console.Read();
}
catch (DivideByZeroException ex)
{
Console.WriteLine("This is divide by zero exception.");
}
catch (OverflowException ex)
{
Console.WriteLine("This is overflow excpetion.");
}
catch (FormatException ex)
{
Console.WriteLine("This is invalid cast exception.");
}
Console.Read();
}
}
}
Exceptions