An exception breaks the normal flow of execution
One mechanism to transfer control, or raise an exception, is known as a throw
Execution is transferred to a "catch"
Exceptions in .NET
Centralized mechanism for handling errors or unusual events
Substitute procedure-oriented approach
Simplify code construction
In C# exceptions are handled with
try-catch-finally blocks
try
{
// Do something
}
catch (Exception)
{
// Do something with the catched exception
}
finally
{
// Executed always but not mandatory
}
There could be multiple catch clauses
The exceptions should be ordered from derived to base
Do not catch generic exceptions (ex: Exception)
try
{
throw new Exception();
}
catch (ArgumentNullException)
{
Console.WriteLine("ArgumentNUllException");
}
catch (Exception)
{
Console.WriteLine("Exception");
}
The exceptions in .NET are organized in a hierarchy
Don not catch Exception class
Just for debugging
When you catch an exception from a particular class
All its ancestors are also caugth
try
{
throw new ArgumentNullException("Null object");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Exception
ArgumentNullException
Base class
Derived class
More about classes (stay tuned)
Ensures that a given block of code will be executed
No matter what happens
You could release(dispose) resources(objects) there
try
{
int a = 5;
int b = a / 0; // Exception
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Executed always");
}
try
{
throw new ArgumentException("Custom message");
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
try
{
var exception = new ArgumentException("My inner exception");
throw new NullReferenceException("Custom message", exception);
}
catch (NullReferenceException e)
{
Console.WriteLine(e.InnerException);
}
try
{
int.Parse(str);
}
catch (FormatException fe)
{
Console.WriteLine("Parse failed!");
throw fe; // Re-throw the caught exception
}