Hey all ok so the issue seems to be at line 45 it seems to be making a loop from the output betting im just doing something wrong with exceptions, sense im just learning them. thanks in advance

/* File Name: Demo.cpp
 Chapter No. 16 - Exercise No. 2
 Programmer:         Carl Sue
 Date Last Modified: Apr 17, 2010
 
 Problem Statement: (what you want the code to do)
 Write a function that accepts an integer parameter and returns its integer
 square root. The function should throw an exception if it is passed an
 integer that is not a perfect square. Demonstrate the function with a
 suitable driver program.

 Input validation: do not accept negative numbers for test scores.
 
 
 Overall Plan (step-by-step how you want the code to make it happen):
 1. accept integer
 2. find square root
 3. return square root if not perfect square throw exception
 etc.
 
 Classes needed and Purpose (Input, Processing, Output):
 
 
 */

#include <iostream>
#include  "Demo.h"
using namespace std;

int sqrt(int);

int main(int argc, char * const argv[]){
	int number, result;
	cout << "enter number: ";
	cin >> number;
	try{
		result = sqrt(number);
	}catch (MyException &e) {
		cout << e.getMessage();
	}
	cout << "Square root is: " << result;
}

int sqrt(int num){
	MyException excp("number is not perfect square");
	cerr <<"got Here!";
	double d_sqrt = sqrt(num);
	int i_sqrt = d_sqrt;
	if ( d_sqrt != i_sqrt ){
		throw excp;
	}
	return sqrt(num);

}

string MyException::getMessage(){
	return message;
}

MyException::MyException(string msg){
	message = msg;
}

.h file

/*
 * Demo.h
 *
 *  Created on: Apr 22, 2010
 *      Author: Carl
 */

#ifndef DEMO_H_
#define DEMO_H_
#include <iostream>
using namespace std;
class MyException {
	public:
		MyException();
		MyException(string msg);
		string getMessage();

	private:
		string message;
	};


#endif /* DEMO_H_ */

Recommended Answers

All 2 Replies

You're getting hit by an unexpected case of the recursions!

int sqrt(int num){
	MyException excp("number is not perfect square");
	cerr <<"got Here!";
	double d_sqrt = sqrt(num);
	int i_sqrt = d_sqrt;
	if ( d_sqrt != i_sqrt ){
		throw excp;
	}
	return sqrt(num);

}

Your exception isn't causing any issue here, but you do continue to call your sqrt function over and over and over again. It keeps printing out your cerr because the function is being called by itself every time it gets into itself.

ha ha lol how did i miss that

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.