Hariharan Hariharan - 3 months ago 13
C++ Question

Try-Catch inside a "for" loop in c++

I've 10 numbers to be read. My task is to generate exceptions with the numbers are either a negative number or a even number. Below is the code I wrote, but it isn't working.

#include <iostream>
using namespace std;

int main()
{
int a[10];
for(int i=0;i<10;i++)
{
cin>>a[i];
}
for(int i=0;i<10;i++)
{
try{
if(a[i]<0 && a%2==0)
throw a[i];
}
catch(int a)
{
cout<<"You ve entered a -ve number or a even number";
}
}
return 0;
}


This was the error shown:

In function 'int main()': 16:24: error: invalid operands of types 'int [10]' and 'int' to binary 'operator%'


Thanks for the help!

Answer

Two things:

  1. You are modulo-ing an array a with an integer 2. You should dereference it to get the value: a[i] % 2 == 0.
  2. You do a boolean AND, where you want a boolean OR (according to your question): || instead of &&.