How C++ exceptions can be caught and re-thrown to be handled by higher-level functions?
How exceptions can be caught and re-thrown to be handled by higher-level functions?
17516-Aug-2023
Updated on 17-Aug-2023
Home / DeveloperSection / Forums / How exceptions can be caught and re-thrown to be handled by higher-level functions?
How C++ exceptions can be caught and re-thrown to be handled by higher-level functions?
Aryan Kumar
17-Aug-2023Exceptions can be caught and re-thrown to be handled by higher level functions in C++ using the
throw
keyword. Thethrow
keyword is used to throw an exception. The exception can be any object, but it is usually astd::exception
object or a derived class ofstd::exception
.To catch and re-throw an exception, you can use the
catch
statement. Thecatch
statement specifies the type of exception that you want to catch. If an exception of the specified type is thrown, thecatch
statement will be executed.The following code shows how to catch and re-throw an exception:
C++
In this code, the
foo()
function throws astd::runtime_error
exception. Thebar()
function catches this exception and then re-throws it. Themain()
function catches the exception and prints a message to the console.It is important to note that the
re-thrown
exception will be caught by the firstcatch
statement that matches its type. If there is nocatch
statement that matches the type of the exception, the program will terminate.Here are some additional things to keep in mind when catching and re-throwing exceptions:
catch
statement by using the|
operator. For example, the following code catches bothstd::runtime_error
andstd::logic_error
exceptions:C++
You can also catch a wildcard exception by using the
catch (...)
statement. Thecatch (...)
statement will catch any exception, regardless of its type.It is important to handle all exceptions that are thrown by your code. If an exception is not handled, the program will terminate.