Function try-catch blocks
source link: https://vorbrodt.blog/2019/04/02/function-try-catch-blocks/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Function try-catch blocks
Syntactic sugar or a useful feature? More than just sweet sweet sugar baby! This little known feature is a nice way of wrapping an entire function in a try catch block. So instead of writing this:
You can write this:
The meaning of the two functions is identical. Notice here I’m swallowing the exception instead of propagating it out. I could call throw to re-throw it, or in both cases I could throw a different exception inside the catch block.
The caveat is with function try-catch blocks around constructors: they have to re-throw the same or different exception. If you don’t re-throw explicitly the compiler will do it for you. It is also useful for catching exceptions emitted during the initialization of member variables, and throwing something else (or re-throwing the same). Like this:
Complete listing (try_block.cpp):
Swallowing: System error from eat_it()
Swallowing: System error from eat_it_sugar()
Inside Q::Q() caught: Logic error from P::P()
Inside main() caught: Runtime error from Q::Q()Program output.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK