In: Computer Science
Exceptional task in c++ OOP: 1. Create three exceptions classes / structures, for division by zero, first second for out of range, third for reading file that doesn't exist. Secure given code with self-made exceptions
Hi,
Please find the code below :
***************************************************************************
1.) For Division By Zero:-
Code:-
#include <iostream>
#include <stdexcept>
#include <bits/stdc++.h>
using namespace std;
//handling divide by zero
float Result(float input, float divisor){
if (divisor == 0) {
throw runtime_error("Math error: Attempted to divide by Zero\n");
}
return (input / divisor);
}
//Driver Function
int main(){
float divident, divisor, result;
divident = 14.5;
divisor = 0;
try {
result = Result(divident, divisor);
cout << "The quotient is " << result << endl;
}
catch (runtime_error& e) {
cout << "Exception occurred" << endl << e.what();
}
}
Output:-
******************************************************************************
2) For Out of Range:-
Code:-
#include <iostream>
#include <stdexcept>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main () {
std::vector<int> example(10);
try {
example.at(15) = 100;
} catch (const std::out_of_range& oor) {
std::cerr << "Out of Range error: " << oor.what() << '\n';
}
return 0;
}
Output:-
******************************************************************************
3) For File Does not Exist:-
Code:-
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int gabcd ;
int main () {
FILE * pfile;
int abcd;
pfile = fopen ("donotexist.txt", "rb");
if (pfile == NULL) {
abcd = gabcd;
fprintf(stderr, "Value of errno: %d\n", gabcd);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( abcd ));
} else {
fclose (pfile);
}
return 0;
}
Output:-
******************************************************************************
Please contact me if you need more clarification.
Thank you :)