Search:

Custom Search
_________________________________________________________________

Friday, August 22, 2008

Understanding Exceptions provided by the .NET Framework - Part 1.

The NullReferenceException:

The easiest way to explain how this works is by writing an example. What we are going to do in the following example is quite simple: we are going to create an Object and initialize it with null value. This object contains string public value type that we can malipulate. But in this particulare case, our Object was set to null, so the CLR will catch this particular exception:


Class Person


public class Person

{

public String name;

}

Main:

static void Main(string[] args)

{

try

{

Person p = new Person();

p = null;

p.name = "CoderG";

}

catch (NullReferenceException) {

Console.WriteLine("p set tu null, cannot be referenced");

}

}

Console:


The StackOverflowException:


This exception is catch by the CLR when it runs out of stack memory. Be aware that the CLR has a finite amount of stack space, so if it gets full, the StackOverflowException will catch the exception. An easy way to trigger this is by defining a recursive function that does nothing, just call itself. Eventually, if the stack was infinite, this method will never stop, but because it is finite, the exception catches this:


Main:


static void Main(string[] args)

{

try

{

callMe();

}

catch (StackOverflowException) {

Console.WriteLine("Stack run out of memory!!!!");

}

}

public static void callMe(){

callMe();

}

Console:

1 comment:

nish said...

loved the way you explained things. Much better many here
mba