Is the integer passed to method1
always going to be done so by a programmer, or might it be passed in by the users of your application?
Assert,
for example if your code looks like this:
int i;
if ( condition ) {
i = 1;
}
else {
i = 3;
}
method1(i);
If this is the case, you'd likely want to use an assert
, because it indicates you (the programmer) has made an error. If i = 3
, you want your program to blow up and make it obvious there is a problem in your code, so you can catch it before you release it to your clients.
Throw an exception,
on the other hand, if your code looks like this:
int i;
cin >> i;
method1(i);
You're passing the user's input to the function. You can't anticipate what they might enter. So if it's an invalid value, you should throw an exception or return an error code and handle it accordingly (e.g., print out a message to the user saying they have entered an invalid number).