Exception with a function - c++

try, throw and catch works, however, cout << devide(a,b) << endl occurs an error. How should I modify this code?
#include "stdafx.h"
#include <iostream>
using namespace std;
double devide(double a, double b) throw(int)
{
double result;
if (b == 0) throw 0;
result = a / b;
return result;
}
int main()
{
int a, b;
cin >> a >> b;
try {
devide(a, b);
}
catch (int c) {
cout << 100 << endl;
}
cout << devide(a,b) << endl;
return 0;
}

First of all throwing int is terrible idea, you should throw exception and there's header for it. You can write your own exceptions if you want but that doesn't matter right now.
Exceptions are for error handling don't use throws to "return different type" from functions and to do such barbaric things. You should throw only when there's no other way around.
In my example bellow I use std::logic_error because I think it suits the situation the best, since dividing by zero violates logical preconditions of any dividing function.
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
// you cannot divide by zero so you are throwing exception
// to handle this edge case which has no mathematical solution
throw logic_error("division by zero.");
}
return a / b;
}
int main() {
int a = 0,
b = 0;
cin >> a >> b;
try {
// result of divide must be evaluated before calling on operator<< of cout
// if it returns (b wasn't 0) it gets called and prints result into cout
// if it throws an exception (b was 0) it gets handled in catch block
cout << divide(a, b) << endl;
} catch (const logic_error& err) {
// printing error message
cout << err.what() << endl; // prints "division by zero."
}
return 0;
}

It is rather pointless to put the call inside a try when you later call it again outside of the try. You probably wanted something like this:
int main() {
int a, b, c;
cin >> a >> b;
try {
c = devide(a, b);
}
catch (exception e) {
c = 100;
}
cout << c << endl;
return 0;
}

#include <iostream>
using namespace std;
double devide(double a, double b)
{
double result;
if (b == 0) throw 0;
result = a / b;
return result;
}
int main()
{
int a, b;
int res=10;
while(res>0){
try {
cin >> a >> b;
devide(a, b);
res=-1;
}
catch (int c) {
cout << 100 << endl;
}
}
}
Put all on a loop and change the condition only in positive case.

Related

Read standard input and print standard output using function bool.getCharacter(char* c)

a. Read single character and print it to standard input.
b. Use the following function to the standard input. The function was bool.getCharacter(char* c).
Here's what I've done so far
#include <iostream>
#include <cstdio>
#define LENGTH 101
int main(void) {
#include <iostream>
using std::cin;
using std::cout;
int main() {
char c;
bool getCharacter(char* c) {
std::cout << &a << " " << a << std::endl;
while(std::cin >> *c) {
if(cin >> *c) {
cout << true << endl;
return 0;
}
else {
cout << false << endl;
return c;
}
return EXIT_SUCCESS;
}
error on line 11: a function-definition is not allowed here before ‘{’ token
Okay, I'm not going to solve all your problems, but let's start with this and see if you get further.
#include <iostream>
#include <cstdio>
#define LENGTH 101
using std::cin;
using std::cout;
bool getCharacter(char* c) {
std::cout << &a << " " << a << std::endl;
if (std::cin >> *c) {
return true;
}
return false;
}
int main(int, char **) {
char c;
while (getCharacter(&c)) {
cout << c << endl;
}
}
Basically, you tried nesting methods, which is really not allowed. And your getCharacter() method was doing way too much. It's supposed to get a character, not do anything else, and then you have to actually call it.

C++ - Exception in Constructor

I have a problem. I must throw an exception in the constructor One() but do not know how do I suppose to catch it. Can someone suggest something? I have tried this method: Throwing exceptions from constructors , What happens if a constructor throws an exception?
My code:
class One
{
int a, b;
public:
One()
{
a = 7;
b = 0;
if (b == 0)
{
throw "except";
}
}
};
int main()
{
One j;
try
{
cout << "good";
}
catch(const char *str)
{
cout << str;
}
}
Place the variable definition inside the try block:
try
{
One j;
std::cout << "good";
}
catch(const char *str)
{
std::cout << str;
}
First of all, don't throw non exception. 2. If you call constructor inside the try block, you can catch it then.
#include <iostream>
#include <stdexcept>
class One
{
int a, b;
public:
One():
a(7),
b(0)
{
if (b == 0) {
throw std::runtime_error("except");
}
}
};
...
try {
One j;
std::cout << "good" << std::endl;
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
}
Another solution if you don't want to have the whole code inside a try..catch block:
int main()
{
One* j = nullptr;
try
{
j = new One;
cout << "good";
} catch (const char *str)
{
cout << str;
return 0;
}
// continue with object in j ...
}
And of course you should a smart pointer in this case:
int main()
{
std::unique_ptr< One> j;
try
{
j.reset( new One()); // or use std::make_unique<>()
cout << "good";
} catch (const char *str)
{
cout << str;
return 0;
}
// continue with object in j ...
}

C++: handling errors, can't understand my mistake [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
1.Check the user input. If the input does not match three floating-point numbers, output an error message and do not start the calculation.
2.Check whether a==0. If so, throw a runtime_error and catch it in main, printing a message saying that a must not be 0.
The error messages should look like this:
An error occured: Malformed user input
An error occurred: a must not be zero
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>
using namespace std;
vector<double> solutionFinal (double a, double b, double c){
double s1, s2, discriminant;
discriminant = b*b - 4*a*c;
if (discriminant > 0){
s1 = (-b + sqrt(discriminant)) / (2*a);
s2 = (-b - sqrt(discriminant)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << s1 << " and " << s2;
return {s1, s2};
}
else if (discriminant == 0) {
cout << "There is 1 solution." << endl;
s1 = (-b + sqrt(discriminant)) / (2*a);
cout << "The solution is: " << s1;
return {s1};
}
else {
cout << "There is no solution." << endl;
return {};
}
}
int main (){
double a, b, c;
cout << "Please enter the values of a, b, and c respectively:" << endl;
try{
if (!(cin >> a >> b >> c)) {
throw runtime_error("An error occured: Malformed user input");
}
if (a == 0) {
throw runtime_error("An erorr occured: a must not be zero");
}
}
auto result = solutionFinal(a, b, c);
for (auto scalar : result){
}
catch (runtime_error& excpt) {
cout << excpt.what();
}
return 0;
}
Your code is malformed, your braces don't add up. I prefer another brace style because I think it's easier to see that way:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>
using namespace std;
vector<double> solutionFinal (double a, double b, double c)
{
double s1, s2, discriminant;
discriminant = b*b - 4*a*c;
if (discriminant > 0)
{
s1 = (-b + sqrt(discriminant)) / (2*a);
s2 = (-b - sqrt(discriminant)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << s1 << " and " << s2;
return {s1, s2};
}
else if (discriminant == 0)
{
cout << "There is 1 solution." << endl;
s1 = (-b + sqrt(discriminant)) / (2*a);
cout << "The solution is: " << s1;
return {s1};
}
else
{
cout << "There is no solution." << endl;
return {};
}
}
int main ()
{
double a, b, c;
cout << "Please enter the values of a, b, and c respectively:" << endl;
try
{
if (!(cin >> a >> b >> c))
{
throw runtime_error("An error occured: Malformed user input");
}
if (a == 0)
{
throw runtime_error("An erorr occured: a must not be zero");
}
// this block was outside the try, between the try and the catch.
// it MUST be inside the try block like this
auto result = solutionFinal(a, b, c);
for (auto scalar : result)
{
}
}
catch (runtime_error& excpt)
{
cout << excpt.what();
}
return 0;
}

Fail to catch exceptions in c++: failure to identify exception type

#include <iostream>
#include <exception>
#include <string>
using namespace std;
int main()
{
try {
cout << "Please input your age: " << endl;
int age;
cin >> age;
if (age > 100 || age < 0) {
throw 130.1;
throw 101;
}
cout << "Good input\n";
}
catch (char e) {
cout << "Wrong input as char " <<e<< endl;
}
catch (int e) {
cout << "Wrong input as int " <<e<< endl;
}
catch (float e) {
cout << "Wrong input as double " <<e<< endl;
}
catch (...) {
cout << "Wrong " << endl;
}
}
Why when I enter 103.1 & 101, exceptions caught go to catch (...) instead of the respective catch(float e) & catch (int e).
130.1 is a double literal, so you need a catch (double) for that one (if you want to throw a float then use throw 130.1f;).
Program control never reaches throw 101;, so catch (int) is redundant.
130.1 is a double literal,
suffix, if present, is one of f, F, l, or L. The suffix determines the type of the floating-point literal:
(no suffix) defines double
f F defines float
l L defines long double
You need to change catch (float e) to catch (double e).
throw 101; is placed after throw 130.1, so it won't be executed at all, then impossible to enter catch (int e) block.

C++ Unexpected number output

EDIT: Fixed the problem thanks to advice from below. Changed the return type of evaluation() from an int to a void.
I'm learning how to use classes, and I'm experiencing a problem. I keep getting an output that says:
0
They are not equal.
4469696
Where is that last number coming from? It should be somewhere after
the line
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
but I don't see anything that could possibly be outputting that value. Is it memory leakage?
#include <iostream>
#include <conio.h>
class classTest
{
public:
int equivalency(int x, int y)
{
if (x == y)
{
value = 1;
} else
{
value = 0;
}
}
int evaluation(int z)
{
if (z == 0)
{
std::cout << "They are not equal." << std::endl;
} else
{
std::cout << "They are equal." << std::endl;
}
}
int getValue()
{
return value;
}
private:
int value;
};
int main()
{
int a = 0, b = 0;
classTest Thing;
std::cout << "Enter two numbers for comparison." << std::endl;
std::cin >> a >> b;
Thing.equivalency(a, b);
std::cout << Thing.getValue() << std::endl;
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
getch();
return 0;
}
In evaluation() you print the expected messages. Then you don't return anything from this function although it is declared to return int, i.e., you get undefined behavior. Further more, you actually point the random result since you output the result of the call:
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
BTW, don't use std::endl! If you want a newline, use '\n', if you want to flush the buffer use std::flush. Unnecessary use of std::endl is a relatively frequent source of major performance problems.