Explain Exception handling

Explain Exception handling

Exception Handling:-# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control. The try, throw, catch, and finally keywords implement exception handling.
Throw:-The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. The throw statement takes the form:
               throw [expression];
where: 

expression :-
The exception object. This is omitted when re-throwing the current exception object in a catch clause.

Try:-
      The try-block contains the guarded code block that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a null object raises the NullReferenceException exception:

object o2 = null;
try
{
   int i2 = (int) o2;   // Error
}
Catch:-
        The catch clause can be used without arguments, in which case it catches any type of exception, and referred to as the general catch clause. It can also take an object argument derived from System.Exception, in which case it handles a specific exception. For example:

catch (InvalidCastException e) 
{
}
Finally:-
         finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.
              The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits. The try-finally statement takes the form:

try try-block finally finally-block
where: 

try-block 
Contains the code segment expected to raise the exception. 
finally-block 
Contains the exception handler and the cleanup code.

By:kamal
Date:2013-10-10 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related C Links

C interview questions and answers for experienced and fresher