{"id":24384,"date":"2025-04-16T09:05:00","date_gmt":"2025-04-16T04:05:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=24384"},"modified":"2025-12-08T11:01:21","modified_gmt":"2025-12-08T06:01:21","slug":"introduction-to-errors-and-exceptions-handling-in-c","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/04\/16\/introduction-to-errors-and-exceptions-handling-in-c\/","title":{"rendered":"Introduction to Errors and Exceptions Handling in C++"},"content":{"rendered":"\n<p>In real-world systems, things often go wrong. A bank server may become unreachable, a file may not open, or a user may enter invalid data. An exception is a runtime event that interrupts the normal flow of a program. Instead of crashing, the program &#8220;throws&#8221; an exception, which gives you a chance to respond.<\/p>\n\n\n\n<p>Exception handling allows programmers to write applications that remain stable even if something unexpected happens.<\/p>\n\n\n\n<p>Imagine you withdraw money from an ATM. If the machine runs out of cash, the system does not crash. Instead, it shows a message like &#8220;Unable to process request.&#8221; This is exception handling in action.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Basics of Exception Handling<\/h1>\n\n\n\n<h2 class=\"wp-block-heading\">The <code>try<\/code> Block<\/h2>\n\n\n\n<p>A <code>try<\/code> block contains the code that might cause an exception.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n    \/\/ risk code\n}\ncatch(...) {\n    \/\/ handle risk\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">The <code>catch<\/code> Block<\/h2>\n\n\n\n<p>A <code>catch<\/code> block captures the exception. It must appear after the <code>try<\/code> block. You can use specific type catches, reference catches or catch-all.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The <code>throw<\/code> Statement<\/h2>\n\n\n\n<p>You use <code>throw<\/code> to manually create an exception when something unexpected occurs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: Division Calculator With Basic try\/catch\/throw<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint main() {\n    int a, b;\n    cout &lt;&lt; \"Enter two numbers: \";\n    cin &gt;&gt; a &gt;&gt; b;\n\n    try {\n        if (b == 0)\n            throw \"Division by zero!\";\n\n        cout &lt;&lt; \"Result = \" &lt;&lt; (a \/ b) &lt;&lt; endl;\n    }\n    catch (const char* msg) {\n        cout &lt;&lt; \"Error: \" &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>Explanation: The program asks the user for two numbers. If the denominator is zero, we throw an exception. The catch block displays the error message without crashing the program.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Standard C++ Exception Types<\/h1>\n\n\n\n<p>C++ has a built-in hierarchy of exceptions based on <code>std::exception<\/code>. Some commonly used exception classes include <code>std::runtime_error<\/code>, <code>std::out_of_range<\/code>, <code>std::invalid_argument<\/code>, and <code>std::bad_alloc<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using Standard Exceptions<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;stdexcept&gt;\nusing namespace std;\n\nint main() {\n    vector&lt;int&gt; nums = {10, 20, 30};\n\n    try {\n        cout &lt;&lt; nums.at(5);\n    }\n    catch (const out_of_range &amp;e) {\n        cout &lt;&lt; \"Exception caught: \" &lt;&lt; e.what() &lt;&lt; endl;\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>Explanation: <code>vector.at()<\/code> throws an exception if the index is invalid. The catch block displays the standard exception message from <code>e.what()<\/code>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Creating Custom Exceptions<\/h1>\n\n\n\n<h2 class=\"wp-block-heading\">Why Create Custom Exceptions?<\/h2>\n\n\n\n<p>In bigger systems (e.g., Hospital Management, Banking Systems), domain-specific errors give clarity. Examples include <code>LowBalanceException<\/code>, <code>InvalidAgeException<\/code>, and <code>FileCorruptException<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to Define a Custom Exception<\/h2>\n\n\n\n<p>You create your own class that inherits from <code>std::exception<\/code> and override the <code>what()<\/code> function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Custom Exception for Invalid Age<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;exception&gt;\nusing namespace std;\n\nclass InvalidAge : public exception {\npublic:\n    const char* what() const noexcept override {\n        return \"Age must be between 18 and 60.\";\n    }\n};\n\nint main() {\n    int age;\n    cout &lt;&lt; \"Enter your age: \";\n    cin &gt;&gt; age;\n\n    try {\n        if (age &lt; 18 || age &gt; 60)\n            throw InvalidAge();\n\n        cout &lt;&lt; \"Age accepted!\" &lt;&lt; endl;\n    }\n    catch (const InvalidAge &amp;e) {\n        cout &lt;&lt; \"Error: \" &lt;&lt; e.what() &lt;&lt; endl;\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>Explanation: Custom exception gives a meaningful message. If the user enters invalid age, the program does not terminate abruptly.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Exception Propagation and Rethrowing<\/h1>\n\n\n\n<p>Exceptions can move from one function to another. If a function cannot handle the error, it can simply throw it upward.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exception Propagation Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nvoid level3() {\n    throw \"File not found!\";\n}\n\nvoid level2() {\n    level3();\n}\n\nvoid level1() {\n    level2();\n}\n\nint main() {\n    try {\n        level1();\n    }\n    catch (const char* msg) {\n        cout &lt;&lt; \"Caught in main: \" &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>Explanation: The exception thrown in <code>level3()<\/code> travels up through <code>level2()<\/code> and <code>level1()<\/code> until it is caught in <code>main()<\/code>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Resource Management and Exception Safety<\/h1>\n\n\n\n<p>One of the biggest reasons to use exception handling is protecting resources such as files, database connections, network sockets, and memory. C++ uses RAII (Resource Acquisition Is Initialization) to prevent resource leaks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Example With File Handling<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\nusing namespace std;\n\nclass FileReader {\n    ifstream file;\n\npublic:\n    FileReader(const string &amp;name) {\n        file.open(name);\n        if (!file)\n            throw \"Unable to open file!\";\n    }\n\n    ~FileReader() {\n        cout &lt;&lt; \"Closing file...\" &lt;&lt; endl;\n        if (file.is_open())\n            file.close();\n    }\n\n    void display() {\n        string line;\n        while (getline(file, line))\n            cout &lt;&lt; line &lt;&lt; endl;\n    }\n};\n\nint main() {\n    try {\n        FileReader fr(\"data.txt\");\n        fr.display();\n    }\n    catch (const char* msg) {\n        cout &lt;&lt; \"Exception: \" &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Smart Pointers and Exception Safety<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;memory&gt;\nusing namespace std;\n\nint main() {\n    try {\n        unique_ptr&lt;int&gt; ptr(new int(10));\n\n        cout &lt;&lt; \"Value: \" &lt;&lt; *ptr &lt;&lt; endl;\n\n        throw \"Some error occurred!\";\n    }\n    catch (const char* msg) {\n        cout &lt;&lt; \"Caught: \" &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>Explanation: <code>unique_ptr<\/code> automatically frees memory even if an exception occurs, preventing memory leaks.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In real-world systems, things often go wrong. A bank server may become unreachable, a file may not open, or a user may enter invalid data. An exception is a runtime event that interrupts the normal flow of a program. Instead of crashing, the program &#8220;throws&#8221; an exception, which gives you a chance to respond. Exception handling allows programmers to write applications that remain stable even if something unexpected happens. Imagine you withdraw money from an ATM. If the machine runs&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/04\/16\/introduction-to-errors-and-exceptions-handling-in-c\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":24387,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[637],"tags":[704,740,739,603],"class_list":["post-24384","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oop-with-c","tag-c","tag-exaptional-handling","tag-exceptionas","tag-oop"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2025\/12\/OOP-2.jpg?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-6li","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/24384","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=24384"}],"version-history":[{"count":1,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/24384\/revisions"}],"predecessor-version":[{"id":24388,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/24384\/revisions\/24388"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/24387"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=24384"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=24384"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=24384"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}