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.
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.
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.
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.
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.
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.
You need to throw an instance of the struct.
void func() {
bad b;
throw b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With