Exceptions are runtime anomalies or abnormal condition that a program encounters during its execution. There are two types of exceptions:
- Synchronous
- Asynchronous
Exceptions which are beyond the program control such as disc failure, keyboard interrupt are called asynchronous exceptions. C++ provides the following specialized keywords for this purpose.
- try: Represents a block of code that can throw an exception.
- catch: Represent a block of code that is executed when a particular exception is thrown.
- throw: Used to throw an exception. Also used to list the exceptions that a function throws but does not handle itself.
The Importance of Exceptions Handling in C++
The following are the main advantages of exception handling over traditional error handling.
- Separation of error handling code from Normal code: With try/catch block, the code for error handling becomes separate from the normal flow.
- Functions/methods can handle only the exceptions they chose. A functions can throw many exception, but may chose to handle some of them. The other exceptions which are thrown but not caught can be handled by the caller. If the caller choses not to catch them, then the exception is handled by the caller of the caller.
- Grouping of error types: In C++, both basic types and objects can be thrown as exceptions. We can create a hierarchy of exception objects, grouping exceptions in namespaces or classes and categorizing them according to their types.
C++ Exception
When executing a C++ code, different error can occur, coding errors made by the programmer, errors due to wrong input or other unforeseeable things. When an error occurs, C++ will always stop and generate an error message. The technical term for this is: C++ will throw an exception.
C++ try and catch
Exception handling in C++ consist of three keyword: try, throw and catch.
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The throw keyword throws an exception when a problem is detected, which let us create a custom error.
The catch statement allows you to define a block of code to be executed if an error occurs in the try block.
Exception Handling in C++
#include <iostream>
using namespace std;
int main()
{
int x = -1;
// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
return 0;
}
Output
Comments (0)