{"id":24384,"date":"2025-04-16T09:05:00","date_gmt":"2025-04-16T04:05:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=24384"},"modified":"2026-05-13T07:04:10","modified_gmt":"2026-05-13T02:04:10","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>Software systems do not always behave perfectly during execution. A banking application may lose connection to the server, a file may fail to open, or a user may enter invalid data. These situations occur while the program is running and can interrupt the normal flow of execution. Such abnormal runtime situations are called exceptions.<\/p>\n\n\n\n<p>If these situations are not handled properly, the program may terminate unexpectedly. Modern software systems therefore use exception handling mechanisms to detect errors and respond safely instead of crashing completely.<\/p>\n\n\n\n<p>Consider an ATM system. If the machine temporarily loses communication with the bank server, the system does not suddenly shut down. Instead, it displays a message such as:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Unable to process your request.\nPlease try again later.<\/code><\/pre>\n\n\n\n<p>This controlled response is an example of exception handling.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Why Traditional Error Handling Was Not Enough<\/h1>\n\n\n\n<p>Before exception handling was introduced, programmers usually handled errors using return values or status codes.<\/p>\n\n\n\n<p>Consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint divide(int a, int b)\n{\n    if(b == 0)\n        return -1;\n\n    return a \/ b;\n}\n\nint main()\n{\n    cout &lt;&lt; divide(10, 0);\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>In this program, the function returns <code>-1<\/code> if division by zero occurs. Although this approach appears simple, it creates several problems. A programmer may forget to check the returned value, or <code>-1<\/code> itself may actually be a valid answer in another situation. As software systems grow larger, mixing error-handling logic with normal program logic makes programs difficult to understand and maintain.<\/p>\n\n\n\n<p>To solve this issue, C++ introduced exception handling.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Basic Idea of Exception Handling<\/h1>\n\n\n\n<p>Exception handling in C++ is based on three important keywords:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>try<\/code><\/li>\n\n\n\n<li><code>throw<\/code><\/li>\n\n\n\n<li><code>catch<\/code><\/li>\n<\/ul>\n\n\n\n<p>The idea is straightforward. The risky code is placed inside a <code>try<\/code> block. If an abnormal condition occurs, the program generates an exception using <code>throw<\/code>. The exception is then received and handled inside a <code>catch<\/code> block.<\/p>\n\n\n\n<p>The general structure looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try\n{\n    \/\/ risky code\n}\ncatch(...)\n{\n    \/\/ handling code\n}<\/code><\/pre>\n\n\n\n<p>The <code>try<\/code> block contains the statements that may generate problems. The <code>catch<\/code> block handles the exception so that the program can continue safely.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">First Example \u2014 Division by Zero<\/h1>\n\n\n\n<p>Let us understand the complete process through a simple program.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint main()\n{\n    int a, b;\n\n    cout &lt;&lt; \"Enter two numbers: \";\n    cin &gt;&gt; a &gt;&gt; b;\n\n    try\n    {\n        if(b == 0)\n            throw \"Division by zero is not allowed.\";\n\n        cout &lt;&lt; \"Result = \" &lt;&lt; a \/ b &lt;&lt; endl;\n    }\n\n    catch(const char* msg)\n    {\n        cout &lt;&lt; \"Error: \" &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>In this program, the user enters two numbers. Before division is performed, the program checks whether the denominator is zero. If the denominator becomes zero, the program uses the <code>throw<\/code> statement to generate an exception.<\/p>\n\n\n\n<p>As soon as the exception is thrown, the normal execution of the <code>try<\/code> block stops immediately. Control jumps directly to the <code>catch<\/code> block, where the error message is displayed.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Understanding Program Flow<\/h1>\n\n\n\n<p>Students often misunderstand how control moves during exception handling. It is therefore important to understand the execution flow carefully.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Program starts\n      \u2193\ntry block begins\n      \u2193\nerror occurs\n      \u2193\nthrow statement executes\n      \u2193\nremaining try block skipped\n      \u2193\ncatch block executes\n      \u2193\nprogram continues safely<\/code><\/pre>\n\n\n\n<p>Once an exception is thrown, the remaining statements inside the <code>try<\/code> block are ignored. The program immediately searches for a matching <code>catch<\/code> block.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Throwing Different Types of Exceptions<\/h1>\n\n\n\n<p>In C++, exceptions are actually data values or objects. Different types of data can be thrown depending on the situation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>throw 10;\nthrow 3.14;\nthrow \"Invalid Input\";<\/code><\/pre>\n\n\n\n<p>Because exceptions can have different data types, C++ allows multiple <code>catch<\/code> blocks to handle different situations.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Multiple catch Blocks<\/h1>\n\n\n\n<p>Consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint main()\n{\n    try\n    {\n        throw 10;\n    }\n\n    catch(int x)\n    {\n        cout &lt;&lt; \"Integer exception caught.\" &lt;&lt; endl;\n    }\n\n    catch(double y)\n    {\n        cout &lt;&lt; \"Double exception caught.\" &lt;&lt; endl;\n    }\n\n    catch(...)\n    {\n        cout &lt;&lt; \"Unknown exception caught.\" &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Here, the program throws an integer value. The <code>catch(int x)<\/code> block handles the exception because its type matches the thrown value.<\/p>\n\n\n\n<p>The <code>catch(...)<\/code> block is called the catch-all handler. It handles any exception type that does not match earlier catch blocks. For this reason, it should always appear at the end.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Exception Handling with Functions<\/h1>\n\n\n\n<p>In real software systems, exceptions usually occur inside functions rather than directly inside <code>main()<\/code>.<\/p>\n\n\n\n<p>Consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nvoid divide(int a, int b)\n{\n    if(b == 0)\n        throw \"Division by zero.\";\n\n    cout &lt;&lt; \"Result = \" &lt;&lt; a \/ b &lt;&lt; endl;\n}\n\nint main()\n{\n    try\n    {\n        divide(10, 0);\n    }\n\n    catch(const char* msg)\n    {\n        cout &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>The function <code>divide()<\/code> throws an exception when division by zero occurs. The exception is not handled inside the function itself. Instead, it is handled in <code>main()<\/code>.<\/p>\n\n\n\n<p>This demonstrates an important concept called exception propagation.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Exception Propagation<\/h1>\n\n\n\n<p>When a function cannot handle an exception, the exception automatically moves upward to the calling function. This process is known as exception propagation.<\/p>\n\n\n\n<p>Consider the following execution chain:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>main()\n \u2193\nlogin()\n \u2193\ndatabase()\n \u2193\nfile()<\/code><\/pre>\n\n\n\n<p>If <code>file()<\/code> throws an exception and does not handle it, the exception travels upward through <code>database()<\/code>, then <code>login()<\/code>, until some function finally catches it.<\/p>\n\n\n\n<p>The following example demonstrates this process clearly.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nvoid level3()\n{\n    throw \"File not found!\";\n}\n\nvoid level2()\n{\n    level3();\n}\n\nvoid level1()\n{\n    level2();\n}\n\nint main()\n{\n    try\n    {\n        level1();\n    }\n\n    catch(const char* msg)\n    {\n        cout &lt;&lt; \"Caught in main: \" &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>The exception originates in <code>level3()<\/code>. Since none of the intermediate functions handle it, the exception eventually reaches <code>main()<\/code>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Standard Exception Classes in C++<\/h1>\n\n\n\n<p>C++ already provides many built-in exception classes through the Standard Library. These classes help programmers handle common runtime problems in a professional way.<\/p>\n\n\n\n<p>Some commonly used standard exceptions are:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>runtime_error\nout_of_range\ninvalid_argument\nbad_alloc<\/code><\/pre>\n\n\n\n<p>These classes are derived from the base class <code>std::exception<\/code>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Using Standard Exceptions<\/h1>\n\n\n\n<p>Consider the following example using <code>out_of_range<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\nusing namespace std;\n\nint main()\n{\n    vector&lt;int&gt; nums = {10, 20, 30};\n\n    try\n    {\n        cout &lt;&lt; nums.at(5);\n    }\n\n    catch(const out_of_range &amp;e)\n    {\n        cout &lt;&lt; \"Exception: \" &lt;&lt; e.what() &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>The function <code>vector.at()<\/code> automatically throws an exception if the index is invalid. The <code>what()<\/code> function returns a descriptive error message associated with the exception object.<\/p>\n\n\n\n<p>This approach is much cleaner and more professional than manually checking every condition.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Custom Exceptions<\/h1>\n\n\n\n<p>Large software systems often require application-specific exceptions. For example, a banking system may need exceptions such as:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>LowBalanceException\nInvalidPINException\nAccountBlockedException<\/code><\/pre>\n\n\n\n<p>These custom exceptions make programs easier to understand and maintain.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Creating a Simple Custom Exception<\/h1>\n\n\n\n<p>A custom exception can be created using a normal class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass InvalidAge {};\n\nint main()\n{\n    int age;\n\n    cout &lt;&lt; \"Enter age: \";\n    cin &gt;&gt; age;\n\n    try\n    {\n        if(age &lt; 18 || age &gt; 60)\n            throw InvalidAge();\n\n        cout &lt;&lt; \"Valid age.\" &lt;&lt; endl;\n    }\n\n    catch(InvalidAge)\n    {\n        cout &lt;&lt; \"Invalid age entered.\" &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Here, the program throws an object of class <code>InvalidAge<\/code> whenever the entered age falls outside the valid range.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Professional Custom Exceptions<\/h1>\n\n\n\n<p>In professional C++ programming, custom exceptions are usually derived from <code>std::exception<\/code>.<\/p>\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\n{\npublic:\n\n    const char* what() const noexcept override\n    {\n        return \"Age must be between 18 and 60.\";\n    }\n};\n\nint main()\n{\n    int age;\n\n    cout &lt;&lt; \"Enter age: \";\n    cin &gt;&gt; age;\n\n    try\n    {\n        if(age &lt; 18 || age &gt; 60)\n            throw InvalidAge();\n\n        cout &lt;&lt; \"Age accepted.\" &lt;&lt; endl;\n    }\n\n    catch(const InvalidAge &amp;e)\n    {\n        cout &lt;&lt; e.what() &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>The <code>what()<\/code> function provides a meaningful message describing the problem.<\/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 for using exception handling is protecting system resources such as files, memory, database connections, and network sockets.<\/p>\n\n\n\n<p>Consider a situation where a program opens a file and then an exception occurs before the file is closed. Without proper handling, the file may remain open and cause resource leaks.<\/p>\n\n\n\n<p>C++ solves this problem using destructors and RAII (Resource Acquisition Is Initialization).<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">File Handling Example<\/h1>\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{\n    ifstream file;\n\npublic:\n\n    FileReader(const string &amp;name)\n    {\n        file.open(name);\n\n        if(!file)\n            throw \"Unable to open file.\";\n    }\n\n    ~FileReader()\n    {\n        cout &lt;&lt; \"Closing file...\" &lt;&lt; endl;\n\n        if(file.is_open())\n            file.close();\n    }\n\n    void display()\n    {\n        string line;\n\n        while(getline(file, line))\n            cout &lt;&lt; line &lt;&lt; endl;\n    }\n};\n\nint main()\n{\n    try\n    {\n        FileReader fr(\"data.txt\");\n        fr.display();\n    }\n\n    catch(const char* msg)\n    {\n        cout &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Even if an exception occurs, the destructor executes automatically and safely closes the file.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Smart Pointers and Exception Safety<\/h1>\n\n\n\n<p>Modern C++ provides smart pointers that automatically manage memory.<\/p>\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{\n    try\n    {\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\n    catch(const char* msg)\n    {\n        cout &lt;&lt; msg &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Even though an exception occurs, the smart pointer automatically releases the allocated memory. This prevents memory leaks and improves program safety.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Best Practices<\/h1>\n\n\n\n<p>Exception handling should be used carefully and professionally. Exceptions should represent abnormal situations rather than normal program logic. Meaningful error messages should always be provided so users and developers can easily understand the problem.<\/p>\n\n\n\n<p>It is also recommended to catch exceptions by reference because it improves efficiency and avoids unnecessary copying.<\/p>\n\n\n\n<p>Empty catch blocks should generally be avoided because silently ignoring exceptions can make debugging extremely difficult.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Software systems do not always behave perfectly during execution. A banking application may lose connection to the server, a file may fail to open, or a user may enter invalid data. These situations occur while the program is running and can interrupt the normal flow of execution. Such abnormal runtime situations are called exceptions. If these situations are not handled properly, the program may terminate unexpectedly. Modern software systems therefore use exception handling mechanisms to detect errors and respond safely&#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":2,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/24384\/revisions"}],"predecessor-version":[{"id":44005,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/24384\/revisions\/44005"}],"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}]}}