TRY, CATCH and FINALLY code blocks are used to handle exceptions in application.
Keyword descriptions:
TRY : contains code that can cause exception
CATCH : contains code to be executed if error is happened
FINALLY: contains code to be executed after any of TRY or CATCH is executed
Sequence:
1. TRY block is executed
1.a. If any error happens in code, and if any CATCH block exists, CATCH block is executed.
1.a.1. If any matching CATCH block exist that addressing exception type, it is executed.
Compile error:
CATCH (System.Exception o_exception)
{
code block...
}
catch (System.Exception e1)
{
code block...
}
If an exception is handled in general exception block (above example), inner exception block cause compile error. It is required to nest inner level exceptions before outer level exceptions
OK:
CATCH (System.Exception o_exception)
{
code block...
}
CATCH (System.IndexOutOfRangeException o_exception)
{
code block...
}
1.b. if any CATCH block does not exist, finally block is executed
2. After TRY block, if error is happened: catch block is executed. Otherwise it is skipped.
3. FINALLY block is executed in both case on error happen or not.
Example:
namespace NS_x
{
class CL_x
{
static void Main(string [] args)
{
int[] ary_example = new int[4]{5,7,9,2};
try
{
for (int i = 0; i < 5; i++)//ERROR: will cause exception: ary_example has not 5th item///
{
Console.WriteLine(ary_example); //ERROR happens///
}
}
catch (System.IndexOutOfRangeException o_exception_1_innerException_1)
{
Console.WriteLine("Inner exception is handled: " + o_exception_1_innerException_1.Message);
}
catch (System.Exception o_exception_2_generalException)
{
Console.WriteLine("General exception is handled: " + o_exception_2_generalException.Message);
}
finally
{
Console.WriteLine("Finally block reached");
}
}
}
}