C++23: Error Handling with std::expected

🚀 𝗠𝗼𝗱𝗲𝗿𝗻 𝗖++ 𝗙𝗲𝗮𝘁𝘂𝗿𝗲: 𝗦𝗧𝗗::𝗘𝗫𝗣𝗘𝗖𝗧𝗘𝗗 (𝗖++𝟮𝟯) Error handling has always been an important part of writing 𝗿𝗼𝗯𝘂𝘀𝘁 𝗖++ 𝗰𝗼𝗱𝗲. Traditionally, developers relied on 𝗲𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 or 𝗲𝗿𝗿𝗼𝗿 𝗰𝗼𝗱𝗲𝘀. But both approaches come with trade-offs: ⚠️ 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 can hide control flow ⚠️ 𝗘𝗿𝗿𝗼𝗿 𝗰𝗼𝗱𝗲𝘀 often make APIs 𝗵𝗮𝗿𝗱𝗲𝗿 𝘁𝗼 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 C++23 introduces a modern solution: 𝗦𝗧𝗗::𝗘𝗫𝗣𝗘𝗖𝗧𝗘𝗗. It represents 𝗲𝗶𝘁𝗵𝗲𝗿 𝗮 𝘃𝗮𝗹𝘂𝗲 𝗼𝗿 𝗮𝗻 𝗲𝗿𝗿𝗼𝗿 in a 𝗰𝗹𝗲𝗮𝗿 𝗮𝗻𝗱 𝘁𝘆𝗽𝗲-𝘀𝗮𝗳𝗲 𝘄𝗮𝘆. ❌ 𝗢𝗹𝗱 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 (Error Codes) Developers often returned special values to indicate failure. int divide(int a, int b) { if (b == 0) return -1; // error code return a / b; } This works — but it creates problems. ❌ 𝗘𝗿𝗿𝗼𝗿 𝗰𝗼𝗱𝗲𝘀 𝗺𝗶𝘅 𝗳𝗮𝗶𝗹𝘂𝗿𝗲 𝗮𝗻𝗱 𝘃𝗮𝗹𝗶𝗱 𝗿𝗲𝘀𝘂𝗹𝘁𝘀 ❌ The caller must 𝗴𝘂𝗲𝘀𝘀 𝘄𝗵𝗮𝘁 -𝟭 𝗺𝗲𝗮𝗻𝘀 ✨ 𝗘𝗻𝘁𝗲𝗿 𝗦𝗧𝗗::𝗘𝗫𝗣𝗘𝗖𝗧𝗘𝗗 C++23 introduces a type that can explicitly represent 𝗲𝗶𝘁𝗵𝗲𝗿 𝗮 𝗿𝗲𝘀𝘂𝗹𝘁 𝗼𝗿 𝗮𝗻 𝗲𝗿𝗿𝗼𝗿. #include <expected> std::expected<int, std::string> divide(int a, int b) { if (b == 0) return std::unexpected("division by zero"); return a / b; } Now the function clearly communicates: ✔ 𝗘𝗶𝘁𝗵𝗲𝗿 𝗮 𝘃𝗮𝗹𝗶𝗱 𝗿𝗲𝘀𝘂𝗹𝘁 ✔ 𝗢𝗿 𝗮𝗻 𝗲𝘅𝗽𝗹𝗶𝗰𝗶𝘁 𝗲𝗿𝗿𝗼𝗿 ⚡ 𝗪𝗵𝘆 𝗦𝗧𝗗::𝗘𝗫𝗣𝗘𝗖𝗧𝗘𝗗 𝗶𝘀 𝗽𝗼𝘄𝗲𝗿𝗳𝘂𝗹 ✔ Enables 𝗲𝘅𝗽𝗹𝗶𝗰𝗶𝘁 𝗲𝗿𝗿𝗼𝗿 𝗵𝗮𝗻𝗱𝗹𝗶𝗻𝗴 ✔ Improves 𝗮𝗽𝗶 𝗰𝗹𝗮𝗿𝗶𝘁𝘆 ✔ Avoids 𝗺𝗮𝗴𝗶𝗰 𝗲𝗿𝗿𝗼𝗿 𝘃𝗮𝗹𝘂𝗲𝘀 ✔ Makes failures 𝗽𝗮𝗿𝘁 𝗼𝗳 𝘁𝗵𝗲 𝘁𝘆𝗽𝗲 𝘀𝘆𝘀𝘁𝗲𝗺 🧠 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 Modern C++ is moving toward 𝗲𝘅𝗽𝗹𝗶𝗰𝗶𝘁 𝗮𝗻𝗱 𝘁𝘆𝗽𝗲-𝘀𝗮𝗳𝗲 𝗔𝗣𝗜 𝗱𝗲𝘀𝗶𝗴𝗻. Instead of hiding failures, modern C++ encourages developers to 𝗺𝗼𝗱𝗲𝗹 𝗲𝗿𝗿𝗼𝗿𝘀 𝗱𝗶𝗿𝗲𝗰𝘁𝗹𝘆 𝗶𝗻 𝘁𝗵𝗲 𝘁𝘆𝗽𝗲 𝘀𝘆𝘀𝘁𝗲𝗺. 🏆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Sometimes the best APIs are the ones that 𝗺𝗮𝗸𝗲 𝗶𝗻𝘁𝗲𝗻𝘁 𝗰𝗹𝗲𝗮𝗿. std::expected helps developers write 𝗺𝗼𝗿𝗲 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝘃𝗲, 𝘀𝗮𝗳𝗲𝗿, and 𝗺𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝗮𝗯𝗹𝗲 𝗖++ 𝗰𝗼𝗱𝗲. #CPP #ModernCPP #CPP23 #SoftwareEngineering #Programming #CleanCode — 𝗔𝗕𝗛𝗜𝗦𝗛𝗘𝗞 𝗦𝗜𝗡𝗛𝗔

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories