What is the Exception Handling mechanism in C++ ? What is Try and Catch in C++ ?
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
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”;
}
Related Articles
- What is exception in Java ? explain try and catch in Java ?
- What are the Standard Exceptions in C++ ?
- Can You write your own exeptions in Java ?
- What are the Storage Types for Variables in C++ ?
- What is a Thread ? What is a Runnable object (object which implements java.land.Runnable) in Java ?


