Test 3 : Solution to Q8 Exceptions

### Solution to Q8

```#include <iostream>
using namespace std;

float calcAverageMarks(int marks[], int size);

//Define the two exception classes
class InvalidMarksListException {};
class InvalidMarksException {};

float calcAverageMarks(int marks[], int size) {
//check if size of marks array is 4
if (size != 4)
throw InvalidMarksListException();

//check if all the four marks in the array are in range
if (marks[0] < 0 || marks[0] > 100)
throw InvalidMarksException();
if (marks[1] < 0 || marks[1] > 100)
throw InvalidMarksException();
if (marks[2] < 0 || marks[2] > 100)
throw InvalidMarksException();
if (marks[3] < 0 || marks[3] > 100)
throw InvalidMarksException();

float avg = (marks[0] + marks[1] + marks[2] + marks[3]) / 4.0;
return avg;
}

int main() {
//Test Case 1 - Invalid Marks List
//Comment the code below if running Test Case 2
//start of test case 1
int marks[] = {70,80,90};
try {
float average = calcAverageMarks(marks, 3);
cout << "Average = " << average << endl;
} catch (InvalidMarksListException) {
cerr << "Marks list is not valid " << endl;
}
//end of test case 1

//Test Case 2 - Invalid Marks Exception
//Comment the code below if running Test Case 1
//Uncomment the code below till the end of catch to test
/*int marks[] = {70,80,90,101};
try {
float average = calcAverageMarks(marks, 4);
cout << "Average = " << average << endl;
} catch (InvalidMarksException) {
cerr << "Some of the marks are out of range " << endl;
}*/

}
```
page revision: 0, last edited: 28 Dec 2009 15:51