ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Exception handling
    Object Oriented ProgrammingTopic 23 of 23

    Exception handling

    8 minread
    1,303words
    Intermediatelevel

    Exception Handling in C++

    Exception handling in C++ allows a program to handle runtime errors or exceptional conditions (like dividing by zero, invalid input, or file I/O errors) in a structured and controlled way. Instead of allowing the program to crash when an error occurs, C++ provides a mechanism to detect, report, and recover from exceptions using try, throw, and catch blocks.


    1. Basics of Exception Handling

    The primary components of C++ exception handling are:

    • try block: Contains the code that may throw an exception.
    • throw statement: Used to raise an exception when an error is detected.
    • catch block: Used to handle the exception when it is thrown.

    2. Syntax of Exception Handling

    try {
        // Code that might throw an exception
    } catch (type1 e1) {
        // Code to handle exception of type type1
    } catch (type2 e2) {
        // Code to handle exception of type type2
    } catch (...) {
        // Catch-all block for any exception type
    }
    
    • try: The try block encloses the code where exceptions might be thrown.
    • catch: Each catch block is used to catch and handle specific types of exceptions.
    • catch(...): The catch-all block catches any exception that doesn't match a previous catch block.

    3. Example of Exception Handling

    Here’s a simple example to demonstrate how exceptions are thrown and caught in C++.

    #include <iostream>
    using namespace std;
    
    // Function that throws an exception
    void testFunction(int number) {
        if (number == 0) {
            throw "Division by zero error!"; // Throwing an exception
        }
        cout << "Result: " << 100 / number << endl;
    }
    
    int main() {
        try {
            testFunction(0);  // This will throw an exception
        } catch (const char* msg) {
            cout << "Caught an exception: " << msg << endl;  // Handle the exception
        }
    
        return 0;
    }
    

    Explanation:

    • The testFunction throws an exception if the argument is zero.
    • The throw statement is used to raise an exception, and the exception type is specified (const char* in this case).
    • The catch block catches the exception and handles it by printing an error message.

    Output:

    Caught an exception: Division by zero error!
    

    4. Types of Exceptions

    Exceptions can be categorized into several types. Common exception types include:

    • Standard exceptions: C++ provides a set of predefined exception classes in the <stdexcept> header.

      • std::exception: The base class for all standard exceptions.
      • std::runtime_error: A general exception for runtime errors.
      • std::out_of_range: Thrown when a container or array index is out of bounds.
      • std::invalid_argument: Thrown when an invalid argument is passed to a function.
    • Custom exceptions: You can define your own exception classes by inheriting from std::exception or other exception classes.


    5. Catching Multiple Exceptions

    You can catch multiple types of exceptions by using multiple catch blocks. C++ will check the exceptions in the order in which they are listed.

    Example: Catching Multiple Exceptions

    #include <iostream>
    #include <stdexcept>
    using namespace std;
    
    void testFunction(int number) {
        if (number == 0) {
            throw runtime_error("Runtime error: Division by zero!");  // Throw runtime_error
        } else if (number < 0) {
            throw invalid_argument("Invalid argument: Negative number!");  // Throw invalid_argument
        }
        cout << "Result: " << 100 / number << endl;
    }
    
    int main() {
        try {
            testFunction(0);  // This will throw a runtime_error
        } catch (const runtime_error& e) {
            cout << "Caught runtime_error: " << e.what() << endl;
        } catch (const invalid_argument& e) {
            cout << "Caught invalid_argument: " << e.what() << endl;
        }
    
        return 0;
    }
    

    Explanation:

    • testFunction throws a runtime_error if the input is zero and an invalid_argument if the input is negative.
    • The catch blocks are used to handle these specific types of exceptions.

    Output:

    Caught runtime_error: Runtime error: Division by zero!
    

    6. The what() Method

    The what() method is defined in the std::exception class. It returns a C-style string (a const char*) that describes the exception.

    • You can call what() inside a catch block to print an exception's message.

    Example: Using what() Method

    #include <iostream>
    #include <stdexcept>
    using namespace std;
    
    void testFunction(int number) {
        if (number == 0) {
            throw runtime_error("Division by zero error!");
        }
        cout << "Result: " << 100 / number << endl;
    }
    
    int main() {
        try {
            testFunction(0);  // This will throw a runtime_error
        } catch (const runtime_error& e) {
            cout << "Caught an exception: " << e.what() << endl;  // Print the exception message
        }
    
        return 0;
    }
    

    Output:

    Caught an exception: Division by zero error!
    

    7. The throw Keyword

    The throw keyword is used to throw an exception. You can throw any type of object, but exceptions are often instances of classes derived from std::exception or built-in types like int or char*.

    Example: Throwing Custom Exceptions

    #include <iostream>
    using namespace std;
    
    // Custom exception class
    class MyException : public exception {
    public:
        const char* what() const noexcept override {
            return "My custom exception occurred!";
        }
    };
    
    void testFunction(bool throwError) {
        if (throwError) {
            throw MyException();  // Throw custom exception
        }
        cout << "No exception occurred!" << endl;
    }
    
    int main() {
        try {
            testFunction(true);  // This will throw MyException
        } catch (const MyException& e) {
            cout << "Caught: " << e.what() << endl;  // Handle custom exception
        }
    
        return 0;
    }
    

    Output:

    Caught: My custom exception occurred!
    

    8. Nested Try-Catch Blocks

    You can have nested try-catch blocks, where one try block is inside another. The inner catch block handles exceptions that occur within the nested try block.

    Example: Nested Try-Catch

    #include <iostream>
    using namespace std;
    
    void testFunction() {
        try {
            cout << "Inside inner try block." << endl;
            throw runtime_error("Error occurred in inner block.");
        } catch (const runtime_error& e) {
            cout << "Caught in inner catch: " << e.what() << endl;
            throw;  // Rethrow the exception to be caught by outer catch
        }
    }
    
    int main() {
        try {
            testFunction();  // Call function that throws an exception
        } catch (const runtime_error& e) {
            cout << "Caught in outer catch: " << e.what() << endl;
        }
    
        return 0;
    }
    

    Output:

    Inside inner try block.
    Caught in inner catch: Error occurred in inner block.
    Caught in outer catch: Error occurred in inner block.
    

    9. Re-throwing Exceptions

    Re-throwing an exception is done using the throw keyword without specifying an exception object. This is typically used to catch and log an exception and then pass it along to be handled elsewhere.

    Example: Re-throwing an Exception

    #include <iostream>
    using namespace std;
    
    void testFunction() {
        try {
            throw runtime_error("Runtime error in testFunction!");
        } catch (const runtime_error& e) {
            cout << "Caught exception: " << e.what() << endl;
            throw;  // Re-throw the exception
        }
    }
    
    int main() {
        try {
            testFunction();  // This will re-throw the exception
        } catch (const runtime_error& e) {
            cout << "Caught in main: " << e.what() << endl;
        }
    
        return 0;
    }
    

    Output:

    Caught exception: Runtime error in testFunction!
    Caught in main: Runtime error in testFunction!
    

    10. Summary

    • try-catch blocks allow you to handle exceptions in a structured way, improving program robustness.
    • throw is used to throw exceptions, and catch is used to handle them.
    • Multiple catch blocks can be used to handle different types of exceptions.
    • The what() method of the std::exception class provides detailed information about the exception.
    • You can re-throw exceptions to pass them to higher levels in the program.
    Previous topic 22
    Data and object serialization using object streams

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,303
      Code examples0
      DifficultyIntermediate