Skip to main content
gamedev.net
🔒 Locked

Exception Handling[solved]

Started by Ilankt 4 replies 950+ views
Original Post
Ilankt
Ilankt

#include <cstdlib>
#include <iostream>
using namespace std;

int divide(int x,int y)
{
    if (y==0)
    {
        throw "divide by zero";
    }
    else
    {
        return x/y;
    }
}

int main(int argc, char *argv[])
{
    try
    {
        divide(1,0);
    }
    catch(char *msg)
    {
        cout<<msg<<endl;
    }
    system("pause");
    return 0;
}


and when I try to run this program, the console just exit immediatly... Is there something wrong with my code or it's the compiler, or this is how it suppose to happen? [Edited by - Ilankt on April 9, 2005 5:57:29 AM]
How appropriate, you fight like a cow!
Illco
Illco
The catch clauses define what to catch by type. It is very error prone to work with this kind of strings. The string you throw (and create by stating its text) has type 'const char*' while you catch 'char*'. I suggest creating a class in which you store such an error message, and throw that instead.

Greetz,

Illco
Ilankt
Ilankt
Thanks.
How appropriate, you fight like a cow!
markr
markr
This is the problem with these forums.

People immediately assume that their tools are broken and that they are right. Whilst it's occasionally the case, mostly tools are not broken.

You are throwing a const char * - you have to catch a const char *, otherwise Dev-C++ (or the underlying compiler) will run into some code for an unhandled exception dropping out of main. Probably it will abort.

This is the right thing to do, it is working perfectly.

A const char * is a MORE SPECIFIC type than a char * - that's to say, you can convert a char * into a const char *, but not vice versa.

Therefore, when the compiler checks whether a const char * IS a char *, it comes to the conclusion that it isn't.

Mark
Ilankt
Ilankt
markr, please take a deep breath
I said in my post that this could be (and probably is) MY fault.
the thing is that I checked also throwing numbers and it didnt worked (and by not working I mean the console is showing for 0.5 seconds on the screen)
but it was probably because he didnt knew what kind of type of number I threw.
now I understand thanks to you and Illco that the problem is that the compiler is very strict about what type of variables you throw, because this is the first time I can remember that the compiler is not handling char * the same as a const char *.
Thanks.
How appropriate, you fight like a cow!
Illco
Illco
Good. Now you've learned that, a bit of relief. You can catch anything by:
try{  // Do your hacky error-prone stuff here  // ...}catch( ... ){}


The disadvantage is that you have no way of retrieving the exception actually thrown, afaik. It is usually used as a 'last deafult case' after catching all specific types.

Greetz,

Illco

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.