Click here to Skip to main content
15,889,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
int x = 1;
     try{
         if(x == 1){
             throw 99;
         }
         cout << "Hey" << endl;
     }
     catch(int err){
         cout << err << endl;
     }

Hey, recently I was studying exception handling in C++ and I wrote the above. However, this code just says terminate called after throwing an instance of 'int'. I guess this should be printing 99. I don't know why this is not working. Please help me. I'll be really grateful. Thank you.

What I have tried:

I have tried searching Google for the correct syntax, but I think my syntax is right and the is not giving the expected output.
Posted
Updated 1-Feb-22 7:24am
v4
Comments
Richard MacCutchan 31-Jan-22 9:22am    
I just tried that exact code and it works fine. I guess the problem is in the code that you are not showing us.
Greg Utas 31-Jan-22 10:51am    
It's not going to fix your problem, whatever it is, but exceptions should be caught by reference: catch(int& err). It won't matter for an int, but it can be important when the exception is an object.

I was doing "#define int long long" to avoid overflow of int in competitive programming. After removing that line it did work. Thanks everyone who replied. :)
 
Share this answer
 
Comments
Joe Woodbury 31-Jan-22 17:15pm    
The issue aside, why not use int64_t?
Greg Utas 31-Jan-22 20:29pm    
Redefining a keyword is naughty. And many uses of #define are undesirable. It's fine in your own code, but not in code that others also use.
CPallini 1-Feb-22 2:11am    
"#define int long long"
I hear crying. I hear the God of the C++ programming language crying.
If I try it (with minor mods because I don't have your "nl" value):
C++
#include <iostream>

using namespace std;

int main(){
    cout<<"Hello World\n";
    int x = 1;
    try{
        if(x == 1){
            throw 99;
        }
        cout << "Hey\n";
    }
    catch(int err){
        cout << err << "\n";
    }
    cout<<"Goodbye\n";
    return 0;
}
It does exactly what I expected it to:
Hello World
99
Goodbye

...Program finished with exit code 0
Press ENTER to exit console.
So ... what am I doing that you aren't?
 
Share this answer
 
v2
Comments
Siddharth Saurav - IIT [BHU] 31-Jan-22 12:26pm    
Oh got it. Actually I was doing "#define int long long" to avoid overflow in competitive programming. After removing that line it did work. Thanks btw. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900