Unit 3 Dot Net Exception
Unit 3 Dot Net Exception
Figure 5-3. Object graphs are constructed to determine which objects are
reachable by application roots.
.
• Once an object has been marked for termination (C and F in this
case—as they are not accounted for in the object graph), they are
swept (REMOVED) from memory.
• At this point, the remaining space on the heap is compacted,
which in turn will cause the CLR to modify the set of active
application roots to refer to the correct memory location (this is
done automatically and transparently).
Understanding Object Generations
• When the CLR is attempting to locate unreachable objects, it does
not literally examine each and every object placed on the managed
heap, doing so would involve considerable time, especially in larger
(i.e., real-world) applications.
• To help optimize the process, each object on the heap is assigned to
a specific “generation.” The idea behind generations is simple: The
longer an object has existed on the heap, the more likely it is to stay
there. For example, the object implementing Main() will be in
memory until the program terminates.
• objects that have been recently placed on the heap are likely to be
unreachable rather quickly (such as an object created within a
method scope). Given these assumptions, each object on the heap
belongs to one of the following generations:
• Generation 0: Identifies a newly allocated object that has
never been marked for collection
• Generation 1: Identifies an object that has survived a
garbage collection (i.e., it was marked for collection, but
was not removed due to the fact that the sufficient heap
space was acquired)
• Generation 2: Identifies an object that has survived more
than one sweep of the garbage Collector.
The garbage collector will investigate all generation 0
objects first. If marking and sweeping these objects results
in the required amount of free memory, any surviving
objects are promoted to generation.
The System.GC Type
• The base class libraries provide a class type named System.GC
that allows you to programmatically interact with the garbage
collector using a set of static members. The only time you will
make use of the members of System.GC is when you are
creating types that make use of unmanaged resources.
• Table 5-1. Select Members of the System.GC Type
class GFG {
In the code given above, the array named ‘arr’ is defined for 5 elements,
indices 0 to 4. When we try to access the 7th element of the array, that is non-
existent, program code throws an exception and the above message is
displayed. The exception can be handled using the System.Exception class of
C#. This will be depicted in the code given below.
Exception Handling Using try-catch block
• The code given below shows how we can handle exceptions using the try-
catch block. The code that may generate an exception is placed inside the
try block.
• In this case, the access to the 7th element is put inside the try block. When
that statement is executed an exception is generated, which is caught by the
catch block. The object of the type IndexOutOfRangeException is used to
display a message to the user about the exception that has occurred.
Syntax:
try {
// statements that may cause an exception
}
catch( Exception obj) {
// handler code
}
using System;
class Program : System.Exception {
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
try {
// Try to access invalid index of array
Console.WriteLine(arr[7]);
// An exception is thrown upon executing the above line }
catch (IndexOutOfRangeException e) {
// The Message property of the object
// of type IndexOutOfRangeException
// is used to display the type of exception
// that has occurred to the user.
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
}
}
Output
1
2
3
4
5
An Exception has occurred : Index was outside the bounds of the array.
Source Returns the name of the assembly that threw the exception.
StackTrace Contains a string that identifies the sequence of calls that
triggered the exception. This is a read-only property.
TargetSite Returns a Method-Base type, which describes numerous
details about the method that threw the exception (ToString()
will identify the method by name). This is a read-only
property.
Throwing a Generic Exception
During the program, if any exception occurs, we can throw it to
either a specific exception like FileNotFoundException,
ArrayIndexOutOfBoundException, DivideByZeroException etc.
or we can through a generic exception directly using Exception
class. The object of Exception class can handle any type of
exception, as it is a base class for all type of exceptions.
using System;
class Test {
int Max=100;
public void Fun(int d) {
if(d>Max)
throw new Exception("crossed limit!!!");
else
Console.WriteLine("d={0}", d); }
public static void Main()
{
Test ob=new Test();
Console.WriteLine("Enter a number:");
int d=int.Parse(Console.ReadLine());
ob.Fun(d);
}
}
Output:
Enter a number: 12
d=12
Enter a number: 567
Unhandled Exception: System.Exception: crossed limit!!!
at Test.Fun(Int32 d)
at Test.Main()
In the above example, if the entered value d is greater than 100, then we are
throwing an exception. We are passing message “crossed limit” to a Message
property of Exception class.
Deciding exactly what constitutes throwing an exception and when to throw an
exception is up to the programmer.
Catching Exceptions
When a block of code is bound to throw an exception, it needs to be caught
using catch statement. Once we catch an exception, we can invoke the
members of System. Exception class. Using these members in the catch block,
we may display a message about the exception, store the information about the
error in a file, send a mail to administrator etc. For example,
using System;
class Test
{
int Max=100;
public void Fun(int d)
{
try
{
if(d>Max)
throw new Exception("crossed limit!!!");
}
catch(Exception e)
{
Console.WriteLine("{0}", e.Message);
}
Console.WriteLine("d={0}", d);
}
public static void Main()
{
Test ob=new Test();
Console.WriteLine("Enter a number:");
int d=int.Parse(Console.ReadLine());
ob.Fun(d);
}
}
Output:
Enter a number: 12
d=12
Enter a number: 123
crossed limit!!!
d=123
• In the above example, we are throwing an exception if d>100
and is caught. Throwing an exception using the statement –
try {
// Constructor
public DivByZero()
{
Console.Write("Exception has occurred : ");
}
}
class Program {