Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to handle divide by zero exception using runtime_error in class with C++

1 Answer

0 votes
#include <iostream>
#include <stdexcept>

using std::cout;
using std::endl;
using std::runtime_error; 

class DivideByZero : public runtime_error {
public:
	DivideByZero::DivideByZero() : runtime_error("divide by zero") {}
};
  
double divide(int x, int y) {
	if (y == 0)
		throw DivideByZero(); 
	
	return static_cast< double >(x) / y;
} 

 int main()
 {
	int n = 13; 
	double result; 
	
	int i = 0;
	while (i++ < 2)
	{
		try {
			   result = divide(n, i - 1);
			   cout << result << endl;
		} 
		catch (DivideByZero &DivideByZero)
		{
			cout <<  DivideByZero.what() << endl;
		} 
		
	} 
	cout << endl;
	
	return 0; 
} 


/*
run:

divide by zero
13

*/

 



answered Jun 4, 2018 by avibootz

Related questions

1 answer 171 views
1 answer 184 views
1 answer 119 views
119 views asked Oct 8, 2022 by avibootz
1 answer 149 views
149 views asked Mar 7, 2017 by avibootz
1 answer 133 views
1 answer 139 views
...