Shreyash Kalaskar 19 Oop10
Shreyash Kalaskar 19 Oop10
Aim :Write a program containing a possible exception. Use a try block to throw
it and catch block to handle it properly.
Theory :
C++ Exceptions:
When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The
technical term for this is: C++ will throw an exception (throw an error).
Exception handling in C++ consists of three keywords: 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 lets
us create a custom error.
We use the try block to test some code: If the age variable is less than 18, we will
throw an exception, and handle it in our catch block.
In the catch block, we catch the error and do something about it. The catch
statement takes a parameter: in our example we use an int variable (myNum)
(because we are throwing an exception of int type in the try block (age)), to
output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than
18), the catch block is skipped:
#include <iostream>
using namespace std;
int main()
{
int x = -1;
There is a special catch block called ‘catch all’ 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.
#include <iostream>
using namespace std;
int main()
{
try {
throw 10; }
catch (char *excp) { cout <<
"Caught " << excp;
}
catch (...) { cout <<
"Default Exception\n";
}
return 0;
}
Output :
Implicit type conversion doesn’t happen for primitive types. For example,
in the following program ‘a’ is not implicitly converted to int
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught " << x;
}
catch (...) { cout <<
"Default Exception\n";
}
return 0;
}
0utput:
Result :Thus , we successfully performed the practical.