• Exception Handling Basics
• Exception Handling mechanism
• Throwing Exception
• Catching exception
• Rethrowing Exception
• Exception Specification
Exception Handling
• Exception are the errors that occur at run time and can stop the working of the program abruptly.
• They can occur in various situations- one such condition when the number is divided by 0.
• For handling such exceptions we have an error handling mechanism called as exception handling.
Objective
Main objective is to provide a way to detect and report the exception condition so that necessary action can be taken without troubling user
Exception handling mechanism
• when exception occurs the portion of program that detects the exception can inform that exception have occurred by throwing it.
• When we throw an exception, program control immidiately stops the step by step execution of code and jumps to exception handler.
• Exception handler catches the exception and process it without troubling user
• When there is no exception handler,program terminates abruptly.
3 constructs used
• Try, Catch, Throw are 3 constructs used for implementing exception handling
• We need to create try and catch block to handle such an exception.
• Try Block: we define the statement that needs to be tested for exception.if exception occurs we use throw statement to invoke exception handler.
Exception handler
• Exception handler is the catch block which catches the exception and process it.
• Syntax: try {// testing condition
Throw excp;
}
catch(datatype arg)
{
//code for handling exception
}
Try-catch block
• the statements in try block can cause exception at run time. On detecting exceptions it is thrown using throw statement in try block.
• Throw keyword is only way to throw an exception and excp represents type of value that can be thrown • Catch block is an exception handler. Block starts with catch keyword.
• Catch