Compilation question with exception handling

Today in class, the teacher was talking about exception handling.

I'm a Linux user so I use the g++ compiler.
But I also have Virtual Studios installed on a Virtual Machine

He wrote some code that apparently in the g++ compiler wouldn't catch the thrown error message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

float divide(float n, float d){
  if(d == 0) throw "Error: divide by zero atempted";
  return n/d;
}


int main(){

try
{
  float result = divide(10,2);
  cout << "The result is: " << result << endl;
  float result2 = divide(10,0);
  cout << "The result2 is: " << result2 << endl;
}
catch (char* ex)
{
  cout << ex << endl;
}

cout << "We stayed alive" << endl;


  return 0;
}


Yeah it would just crash, but when I compiled it with VS it caught it correctly.

Can someone explain?

What can I change so that it runs with g++
Last edited on
The type of the literal string "Error: divide by zero atempted" is 'array of n const char'

To catch the exception, catch with catch( const char* ) { ...


> when I compiled it with VS it caught it correctly

With the Microsoft compiler, disable Microsoftisms with the compiler option /Za (Disable language extensions).

With the GNU compiler, disable Linuxisms with both -std=C++14 (the language really is C++)
and -pedantic-errors (when I say C++, I mean C++ as defined by the International Standard)
Topic archived. No new replies allowed.