Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ exception handling

Tags:

c++

exception

Learning "try & catch". What is wrong with the following code? Thanks for the advice.

Error in execution:

terminate called without an active exception
Aborted

The code:

#include <stdio.h>
int main()
{
  int a = 3;

  try
  {
    if (a < 5)
      throw;
  }
  catch (...)
  {
    printf ("captured\n");
  }

  return 0;
}
like image 587
user180574 Avatar asked Oct 16 '12 00:10

user180574


2 Answers

Your throw; statement tries to rethrow a current exception but there probably isn't one. You need something like

throw some_exception_object();
like image 64
Dietmar Kühl Avatar answered Nov 02 '22 23:11

Dietmar Kühl


Inside of a try block, you have to specify what to throw. The only place you can use throw by itself is inside of a catch block to re-throw the current exception. If you call throw by itself without a current exception being active, you will kill your app, as you have already discovered.

Try this:

#include <stdio.h> 

int main() 
{ 
  int a = 3; 

  try 
  { 
    if (a < 5) 
      throw 1; // throws an int 
  } 
  catch (...) 
  { 
    printf ("captured\n"); 
  } 

  return 0; 
} 

You can throw anything you want, as long as you throw something.

like image 25
Remy Lebeau Avatar answered Nov 03 '22 01:11

Remy Lebeau