How do you catch an exception in c++? - 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';
}

Related

catch queues overflow exceptions when they occur

void IntQueue::enqueue(int num)
{
if (isFull())
throw std::runtime_error("The queue is full");
else
{
// Calculate the new rear position
rear = (rear + 1) % queueSize;
// Insert new item
queueArray[rear] = num;
// Update item count
numItems++;
}
}
after I throw this exception how can I rewrite the main program so that it catches overflow exceptions when they occur. The exception handler for queue overflow should print an appropriate error message and then terminate the program. here is the main program
int main()
{
IntQueue iQueue(5);
cout << "Enqueuing 5 items...\n";
// Enqueue 5 items.
for (int x = 0; x < 5; x++)
iQueue.enqueue(x);
// Attempt to enqueue a 6th item.
cout << "Now attempting to enqueue again...\n";
iQueue.enqueue(5);
// Deqeue and retrieve all items in the queue
cout << "The values in the queue were:\n";
while (!iQueue.isEmpty())
{
int value;
iQueue.dequeue(value);
cout << value << endl;
}
}
Wrap the part that can throw with try-block.
For example,
try
{
for (int x = 0; x < 5; x++)
iQueue.enqueue(x);
// Attempt to enqueue a 6th item.
cout << "Now attempting to enqueue again...\n";
iQueue.enqueue(5);
}
catch (const std::runtime_error& e)
{
cout << "Error: " << e.what() << endl; // Print error message
exit(1); // Terminate with non-zero exit code
}

Can't catch exception std::stoi

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

C++ crash at try-catch statement

So, I'm doing a homework where we have to test our class. We were forbidden to use stl.:) The problem is that at the test_2 the program crashes. It works all until it gets beck to the main try statement. When it should jump to the exception it just crashes. Any idea why is this happening? Thanks in advance! :)
void test_2() //
{
int tomb[400];
for(unsigned int j=0;j<400;j++){
tomb[j]=j;
}
cout <<"array loaded \n";
Buffer<int> test2(40,"test2.txt","w");
Buffer<int> test21(40,"test21.txt","w"); // 40 meretu buffer
cout << "bufferek letrehozva \n";
for(unsigned int j=0;j<400;j++){
test2[j]=tomb[j];
}
cout << "buff loaded \n";
/* for(unsigned int j=0;j<400;j++){
cout << test2[j] << endl;
} */
test21=test2;
cout << "copy constr ran \n";
unsigned int i=0;
for(unsigned int j=0;j<400;j++){
if(i==39){for(i=0;i<40;i++){ //40 size buff
test21.printfile(test21[i]);}
i=0;}
else i++;
}
throw "gets here";
}
int main()
{
try
{
int number;
cin >> number; // nr of the test
switch (number)
{
case 1:
test_1(); // file_test
break;
case 2:
test_2(); // copyconst_test
break; // crashes here
case 3:
test_3();
break;
}
}
catch (exception& e)
{
cerr << e.what() << endl;
}
catch (int i)
{
cerr << i << endl;
}
catch (const char* s)
{
cerr << s << endl;
}
catch (...)
{
cerr << "*** Nagy baj van! ****" << endl;
}
return 0;
}
SOLVED
I made an obj with the size of 40 and loaded it with 400 int. This procedure made the size of the test2 object 720(becuse at overloading it doubles its size) so I made 2 different sized objects equal.
Buffer<int> test2(40,"test2.txt","w");
// first buffer
cout << "bufferek made\n";
for(unsigned int j=0;j<400;j++){
test2[j]=tomb[j]; //load buffer
}
Buffer<int> test21(test2.getSize(),"test21.txt","w"); //make the second buffer

boost::thread interrupt() throws an exception only the first time that an interruption point is executed?

boost::thread interrupt() throws an exception only the first time that an interruption point is executed? My case is the following.
I create a boost::thread which executes functionA. functionA calls functionB and when on functionB we call function threadInterrupt. functionB throws a boost::thread_interrupted exception and returns to functionA. My question is if a new boost::thread_interrupted exception will be throw in functionA when another interruption point is executed.
void MyClass::function(int arg1, int arg2) try {
boost::thread* t = new boost::thread(boost::bind(&MyClass::functionA, this, var1, var2));
} catch (...) {
cout << "function throw an exception" << endl;
}
void MyClass::functionA(int arg1, int arg2 ) try {
//some code here
try {
int retVal = MyClass::functionB(var);
boost::this_thread::interruption_point();
//some code here
} catch(boost::thread_interrupted&) {
cout << "thread interrupted in functionA" << endl;
}
} catch (...) {
cout << "functionA throw an exception" << endl;
}
int MyClass::functionB(int arg1) try {
//some code here
try {
boost::this_thread::interruption_point();
//some code here
} catch(boost::thread_interrupted&) {
cout << "thread interrupted in functionB" << endl;
return 0;
}
return 1;
} catch (...) {
cout << "functionB throw an exception" << endl;
return 1;
}
void MyClass::threadInterrupt() {
if (thr!=NULL) {
thr->interrupt();
thr->join();
delete thr;
thr=NULL;
}
}
Have you tried it? See it Live On Coliru
#include <boost/thread.hpp>
#include <iostream>
using namespace boost;
int main() {
thread t([]{
int i = 0;
while (true) try {
if (i >= 10) return;
while (i < 10) {
this_thread::sleep_for(chrono::milliseconds(200));
std::cout << "processed " << i++ << "\n";
}
}
catch (...) { std::cout << "Interrupted at i = " << i << "\n"; }
});
this_thread::sleep_for(chrono::milliseconds(800));
t.interrupt();
t.join();
std::cout << "Interrupt requested? : " << std::boolalpha << t.interruption_requested() << "\n";
}
Output:
processed 0
processed 1
processed 2
Interrupted at i = 3
processed 3
processed 4
processed 5
processed 6
processed 7
processed 8
processed 9
Interrupt requested? : false
As you can see the interrupt request behaves like a sort of auto-reset flag.

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");
....