Can't catch exception std::stoi - c++

Whenever I input anything other than an integer, I was hoping for the catch block to execute but instead I get this error:
Unhandled exception at 0x002D0C39 in A03.exe: Stack cookie instrumentation code detected a stack-based buffer overrun. occurred
which takes me to:
Exception thrown at 0x76D44192 in A03.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0116D83C.
Unhandled exception at 0x000608B9 in A03.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.
I've tried varieties of catch blocks and exceptions with the same error. Can someone tell me what I'm doing wrong? Thank you!
Here is the code:
int main() {
while (true) {
std::string input;
int num = 0;
std::cout << "What number do you want to show?";
std::cin >> input;
try
{
num = std::stoi(input);
if (num >= 0 && num < 10)
{
std::cout << "FILLER: This will draw the number";
exit(0);
}
else {
std::cout << "FILLER: This is the else";
exit(1);
}
}
catch (std::runtime_error e)
{
std::cout << e.what();
//std::cout << "That is not a valid number." << '\n';
}
}
return 0;
}
UPDATE: Edited the exception handler, but still erroring:
int main() {
while (true) {
std::string input;
int num = 0;
std::cout << "What number do you want to show?";
std::cin >> input;
try
{
num = std::stoi(input);
if (num >= 0 && num < 10)
{
std::cout << "FILLER: This will draw the number";
exit(0);
}
else {
std::cout << "FILLER: This is the else";
exit(1);
}
}
catch (std::invalid_argument &e)
{
std::cout << e.what();
//std::cout << "That is not a valid number." << '\n';
}
}
return 0;
}

The exception that this function throws is std::invalid_argument, which have the following inheritance connections: std::exception <- std::logic_error <-std::invalid_argument. This means you can use any of the above as the catch type (and also ...), to catch the exception. std::runtime_error is not one of the options (std::exception <- std::runtime_error).
Change your catch section to:
catch (std::invalid_argument &e) {
std::cout << e.what();
//std::cout << "That is not a valid number." << '\n';
}
Read About:
std::invalid_argument
std::runtime_error
std::exception - Exceptions tree

Related

How to create single error handler for multiple catch that are just doing same thing at multiple place and add that error handler inside another file?

I don't have much knowledge of exception.
I have two files task.cpp, main.cpp. Inside task.cpp file, I have a lot try/catch statements. I want to remove all the generic handlers for things like ..., std::exception etc., they are just printing the error, and I want to create just a single error handler of this kind and reside it inside main.cpp. How can I do it ?
These are some part of task.cpp & main.cpp file.
I want to remove catch (...) , catch (Exception const& _exception) from task.cpp file as they are used at multiple steps and create repetitive code
try
{
if (!stack.parseAndAnalyze(src.first, src.second))
successful = false;
else
stack.optimize();
}
catch (Exception const& _exception)
{
serr() << "Exception in assembler: " << boost::diagnostic_information(_exception) << endl;
return false;
}
catch (std::exception const& _e)
{
serr() <<
"Unknown exception during compilation" <<
(_e.what() ? ": " + string(_e.what()) : ".") <<
endl;
return false;
}
catch (...)
{
serr() << "Unknown exception in assembler." << endl;
return false;
}
}
if (_language != yul::AssemblyStack::Language::Ewasm && _targetMachine == yul::AssemblyStack::Machine::Ewasm)
{
try
{
stack.translate(yul::AssemblyStack::Language::Ewasm);
stack.optimize();
}
catch (Exception const& _exception)
{
serr() << "Exception in assembler: " << boost::diagnostic_information(_exception) << endl;
return false;
}
catch (std::exception const& _e)
{
serr() <<
"Unknown exception during compilation" <<
(_e.what() ? ": " + string(_e.what()) : ".") <<
endl;
return false;
}
catch (...)
{
serr() << "Unknown exception in assembler." << endl;
return false;
}
sout() << endl << "==========================" << endl;
sout() << endl << "Translated source:" << endl;
sout() << stack.print() << endl;
}
try
{
object = stack.assemble(_targetMachine);
object.bytecode->link(m_options.linker.libraries);
}
catch (Exception const& _exception)
{
serr() << "Exception while assembling: " << boost::diagnostic_information(_exception) << endl;
return false;
}
catch (std::exception const& _e)
{
serr() << "Unknown exception during compilation" << (
_e.what() ? ": " + string(_e.what()) : "."
) << endl;
return false;
}
catch (...)
{
serr() << "Unknown exception while assembling." << endl;
return false;
}
And catch inside main.cpp file like this:
int main(int argc, char** argv)
{
try
{
setDefaultOrCLocale();
solidity::frontend::CommandLineInterface cli(cin, cout, cerr);
if (!cli.parseArguments(argc, argv) || !cli.readInputFiles() || !cli.processInput() || !cli.actOnInput())
return 1;
return 0;
}
catch (boost::exception const& _exception || Exception const& _exception || InternalCompilerError const& _exception
|| smtutil::SMTLogicError const& _exception)
{
cerr << "Uncaught exception" << boost::diagnostic_information(_exception) << endl;
return 1;
}
catch (std::exception const& _e)
{
cerr() << "Uncaught exception" << (_e.what() ? ": " + string(_e.what()) : ".") << endl;
return 1;
}
catch (Exception const& _exc)
{
cerr() << string("Failed to import AST: ") << _exc.what() << endl;
return 1;
}
catch (...)
{
cerr << "Uncaught exception" << endl;
return 1;
}
}

How do you catch an exception in c++?

I've been trying to output "Queue is full" which was declared in my other code. How do I catch this?
this is my main
int main() {
IntQueue iQueue(5);
try {
cout << "Enqueuing 5 items...\n";
// Enqueue 5 items.
for (int x = 0; x < 5; x++)
iQueue.enqueue(x);
} catch (...) {
// Attempt to enqueue a 6th item.
cout << "Now attempting to enqueue again...\n";
iQueue.enqueue(5);
}
and this is my other code
if (isFull())
throw std::runtime_error("Queue is full");
else {
cout << "Enqueueing: " << num << endl;
// Calculate the new rear position
rear = (rear + 1) % queueSize;
// Insert new item
queueArray[rear] = num;
// Update item count
numItems++;
}
Here is how you catch an exception and print its message:
try {
// ...
} catch (std::runtime_error const& e) {
std::cout << e.what() << '\n'; // or std::cerr, std::perror, or smth else
}
Any code under the catch block is meant to catch any exception thrown in the try block, which means you should write any code that could throw exceptions in it:
try {
// trying to enqueue 6 items, which is above limit.
for (int x = 0; x < 6; x++) {
iQueue.enqueue(x);
}
} catch (exception e) {
cout << e.what() << '\n';
}

c++ No exception thrown while expecting out_of_range

Consider the following source:
void ex8()
{
vector<int> v;
try
{
v.push_back(3);
int i = v[1];
}
catch (exception& e)
{
cout << "pas bon !";
}
}
When executing, no exception is thrown in Release. In Debug, I get a Debug Assertion Failed dialog.
I'am using Visual Studio on Win 10.
Is the vector implementation not supposed to throw an out_of_range exception?
Thank you.
Just an example with [] and at()
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
v.push_back(123);
v.resize(0);
try {
std::cout << "at() ";
std::cout << v.at(0) << std::endl;
}
catch (std::exception e) {
std::cout << e.what() << std::endl;
}
std::cout << "[] " << v[0] << std::endl; // all can append
return 0;
}
For me the execution is
at() std::exception
[] 123

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.

Cascade Poco Exception

I try to cascade exception in Poco.
void debug() {
try {
...
xmlFile.parseDocument(*_sim);
...
}
} catch (Poco::Exception& error) {
std::cout << "I'm here" << endl;
std::cout << "Error : " << error.displayText() << std::endl;
}
}
void XMLParser::parseDocument(Manager &manager) {
...
try {
Poco::XML::NodeList* policyList = root->childNodes();
for (uint node=0; node < policyList->length(); node++)
if (policyList->item(node)->hasChildNodes())
manager.insertRule(parseRule(node, policyList->item(node)));
} catch(Poco::Exception& error) {
std::cout << "Error : " << error.displayText() << std::endl;
error.rethrow();
}
}
Rule* XMLParser::parseRule(int flowID, Poco::XML::Node* rule) throw() {
....
if (tLink._srcPort < 0)
throw new Poco::Exception("Source Port isn't valid");
....
}
The deepest exception are thrown, but it does not continue to outer functions.
The program is terminated. Why?
You throw a Poco::Exception pointer so you can not catch it by reference.
Remove 'new'. This should work:
....
if (tLink._srcPort < 0)
throw Poco::Exception("Source Port isn't valid");
....