- 1
What does the throw syntax actually do in c++??
c++ query
2 Answers
+ 2
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
throw:Â A program throws an exception when a problem shows up.
This is done using a throw keyword.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statements.
The operand of the throw statements determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown.
+ 2
It's used to throw exceptions. This would be an example:
// exceptions
#include <iostream>
using namespace std;
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}
It would output >> An exception occurred. Exception Nr. 20
You can read more about it here: https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm