Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ throw syntax

Tags:

c++

I have a general question regarding the syntax of throwing an object. Consider:

#include <stdio.h>

struct bad { };

void func() {
    throw bad;
}

int main(int, char**) {
    try {
        func();
    } catch(bad) {
        printf("Caught\n");
    }

    return 0;
}

This code does not compile (g++ 4.4.3), as the 'throw' line must be replaced with:

throw bad();

Why is this? If I'm creating a stack-allocated bad, I construct it like so:

bad b;
// I can't use 'bad b();' as it is mistaken for a function prototype

I've consulted Stroustrup's book (and this website), but was unable to find any explanation for what seems to be an inconsistency to me.

like image 885
Kyle Morgan Avatar asked Nov 15 '11 19:11

Kyle Morgan


People also ask

Does C have Throw?

C doesn't support exception handling. To throw an exception in C, you need to use something platform specific such as Win32's structured exception handling -- but to give any help with that, we'll need to know the platform you care about. ...and don't use Win32 structured exception handling.

What is throw in C hash?

In c#, the throw is a keyword, and it is useful to throw an exception manually during the execution of the program, and we can handle those thrown exceptions using try-catch blocks based on our requirements. The throw keyword will raise only the exceptions that are derived from the Exception base class.

How do you throw a statement in C++?

An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block.

What is throw and throws in C++?

C++ try and catch Exception handling in C++ consist of three keywords: try , throw and catch : The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error.


2 Answers

throw bad;

doesn't work because bad is a data type, a structure (struct bad). You cannot throw a data type, you need to throw an object, which is an instance of a data type.

You need to do:

bad obj;
throw obj;

because that creates an object obj of bad structure and then throws that object.

like image 52
Alok Save Avatar answered Oct 28 '22 13:10

Alok Save


You need to throw an instance of the struct.

void func() {
    bad b;
    throw b;
}
like image 43
Nick Rolando Avatar answered Oct 28 '22 13:10

Nick Rolando