Exception Handling - SoS 2023
Exception Handling - SoS 2023
Exception handling
Exception handing in C++
• Exceptions are run-time anomalies or abnormal conditions that a
program encounters during its execution. C++ provides following
specialized keywords for this purpose.
• try: represents a block of code that can throw an exception.
• catch: represents 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 doesn’t handle itself.
Divided by zero exception
int main()
{
float x, y;
cout << "enter numerator \n";
cin>>x;
cout << "enter denominator \n";
cin>>y;
cout<<x/y;
return 0;
}
int main()
{
int x = -1;
cout << "Before try \n";
try {
cout << "Inside try \n";
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
Before try
Inside try
Exception Caught
After catch (Will be executed)
#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
} return (a/b);
}
int main () {
int x = 50; int y = 0; double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cout << msg << endl; } }
Catch Block
• There is a special catch block catch(…) that can be used to catch all
types of exceptions. For example, in the following program, an int is
thrown as an exception, but there is no catch block for int, so
catch(…) block will be executed.
int main()
{
try {
throw 10;
}
catch (char excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
• Output
Default Exception
References
• https://www.geeksforgeeks.org/file-handling-c-classes/
• https://www.geeksforgeeks.org/output-c-programs-set-34-file-
handling/
• https://www.geeksforgeeks.org/exception-handling-c/