An exception means that an action member failed to complete
the task it was supposed to perform. The misconception is that an exception always
identifies an error. The term error implies that the programmer did something
wrong. Therefore only the caller can decide if the results of the call indicate
and error or not.
Exception handling uses the try, catch and finally keywords to attempt actions
that may not succeed, to handle failures and clean up resources afterwards.
Exception can be created using throw
keyword.
No exception handler for a given exception is present, the
program stops executing with an error message. Exception can hold the
information about the error including state of the call stack and text
description of the error.
A finally block is a way to ensure a piece of logic is
always executed before the method is exited.
Try and catch without finally works
try
{
}
finally
{
}
Try and catch works without the parameter
try
{
}
catch
{
}
Just try won’t work. Try always expects finally or catch.
try
{
}
The exception order is matters, when we catch any specific exception
that should be on top the System.Exception always on
bottom. The finally must be in the last.
Even if you use return inside the exception it executes the
finally block before return.
try
{
throw new InvalidCastException();
}
catch (InvalidCastException ex)
{
return;
}
catch (Exception ex)
{
}
finally
{
}
There few restrictions in the finally block. See the below code, it will not allow to put goto /return statement inside the finally block.
The exception classes
·
System.ApplicationException – This is generated by applications. So the developers should use
the class define their own exceptions
·
System.Exceptions – base
class for all the exceptions
List of few framework level exceptions
·
System.IndexOutOfRangeException
·
System.ArrayTypeMismatchException
·
System.NullReferenceException
·
System.DivideByZeroException
·
System.InvalidCastException
·
System.OutOfMemoryException
·
System.StackOverflowException
Few more notes
·
Nested levels of try catch should be avoided if
all they do nothing but log the exceptiosns.
·
Try finally must be used if resource object
doesn’t support IDisposible.
·
The lock
and using statements automatically
generates the try and finally block by the compiler.
·
Don’t use exception as part of our logic
·
Catch the exception at root level, it should be
logged, intermediate level do not catch the exceptions unless you really want.