What is the Exception Handling mechanism in C++ ? What is Try and Catch in C++ ?
The ability to gracefully handle an error or an exception is known as exception handling. C++ has built exception handling techniques which allows the program to handle and exceptions and deal with them.
- try block: the code that is likely to throw an exception should be enclosed in a try lock. This allows the function to recover from this exception. If a code called from a try block cannot throw an exception then there is no need for the try block.
- Catch block: the exception that is thrown in the try block has to be caught in the catch block. There can be multiple catch blocks for a try block however there cannot be any code between try and catch block. Once an exception is caught and if the function can recover from that error then it can either continue normal processing or restart the try block by putting the try block in a loop. If required the catch block can also propagate the exception to the calling function either by throwing the same exception object or throwing a different exception object.
e.g.
try { File x (filename); } catch (BadFileName& e) { cout << " second(): " << e.what() << ": Partial recovery\n"; throw; } catch (AccessViolation& e) { cout << " second(): " << e.what() << ": Full recovery\n"; }

Re: What is the Exception Handling mechanism in C++ ? What is Tr
Exception handling in C++ is complex and subtle. It is not as trivial as the above would make you believe.
If you are interested in learning, go and read Meyers, Sutter/GOTW et al.
For a proper treatment, you need to discuss (at a bare minimum):
- What happens to x when an exception is thrown.
- What happens if the destructor of File throws.
- Why you want to catch by reference.
- What can throw (answer: a lot more than you think).
- RAII.