Professional Documents
Culture Documents
Exception Handlings in C#-DJ
Exception Handlings in C#-DJ
1. Introduction to Exceptions
Exception is an object delivered by the Exception class. This Exception class is exposed by
theSystem.Exception namespace. Exceptions are used to avoid system failure in an unexpected
manner.Exception handles the failure situation that may arise. All the exceptions in the .NET
Framework are derived from the System.Exception class.
To understand exception, we need to know two basic things:
An
1.
2.
Somebody sees a failure situation that happened and throws an exception by packing the valid
information.
Somebody who knows that a failure may happen catches the exception thrown. We call
it ExceptionHandler.
Below is a simple example, which shows what happens when an Exception is not handled:
Hide Shrink
Copy Code
class ExceptionsEx
{
//001: Start the Program Execution.
public void StartProgram()
{
Console.WriteLine("Making Call to F1() " );
F1();
Console.WriteLine("Successfully returned from F1() " );
}
//002: Set of Function that calls each other
public void F1()
{
Console.WriteLine("Making Call to F2() " );
throw new System.Exception();
F2();
Console.WriteLine("Successfully returned from F2() " );
}
public void F2()
{
Console.WriteLine("Inside F2 " );
}
//Client 001: Program Entry
[STAThread]
static void Main(string[] args)
{
//Create the Object and start the Execution
ExceptionsEx app = new ExceptionsEx();
app.StartProgram();
}
}
The above dialog is shown in debug mode, so you may get a chance to break the execution to see where the
2. Handling Exception
To handle the exception, we need to place the code within the
try
{
//Some Code that may expected to raise an exception
}
catch
{
//Raised exception Handled here
}
Hide Shrink
class ExceptionsEx
{
//001: Start the Program Execution.
Copy Code