Link to home
Start Free TrialLog in
Avatar of panJames
panJames

asked on

try... catch problem

Hello Experts!

Please have a look at the code below.

I expect to catch exception, instead I get exception risen by vector code and it crashes my application.

What do I do wrong here?

Thank you

panJames

#include <vector>
#include <iostream>
#include <exception>

using namespace std;

void main()
{
	int a;
	std::vector<int> abc;

	abc.push_back(1);
	abc.push_back(2);

	try
	{
		a = abc[2];
	}
	catch (exception& e)
	{
		cout << e.what();

	}

}

Open in new window

Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

you need to put the try larger:
#include <vector>
#include <iostream>
#include <exception>

using namespace std;

void main()
{
        try
        {
        int a;
        std::vector<int> abc;

        abc.push_back(1);
        abc.push_back(2);

                a = abc[2];
        }
        catch (exception& e)
        {
                cout << e.what();

        }

}

Open in new window

To further angelIII's comment, you only reserved the space--you didn't actually initialize it, so you are trying to call a method on a null object, hence the exception.
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of panJames
panJames

ASKER

@angelIII:

1. Why do I need larger try{} selection? Thought that I need to make my try{} where I expect it to crash...
2. It does not help anyway. Program never comes to line:

 cout << e.what();

@kaufmed: I know it.

panJames
>>  @kaufmed: I know it.


Uhhh...   then you have your answer  = )

Calling a method on an uninstantiated object raises an exception.
@Infinity08:

I am confused now.

My understanding of try{} was that if anything wrong happens inside try{} then exception is thrown and all I need to do is to catch it (like in Delphi).

So C++ program does not have such functionality?

How can I catch something simple like:


int a = 12;
int b = 0;
int c;


try
{
 c = a / b;
}


panJames
>> My understanding of try{} was that if anything wrong happens inside try{} then exception is thrown and all I need to do is to catch it (like in Delphi).

No, not anything. Anything that throws a C++ exception will be caught if you have an appropriate catch handler. But divisions by 0 or segmentation faults eg. won't.


>> So C++ program does not have such functionality?

Some compilers might add it as an extension, but it's not generally available no.