ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2111Exception Handling
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2111

    Object Oriented Programming

    Progress0 / 23 done
    Topics23
    1Introduction to object oriented design2History and advantages of object oriented design3Introduction to object oriented programming concepts4Classes and objects5Data encapsulation6Constructors and destructors7Access modifiers8Const vs non-const functions9Static data members & functions10Function overloading11Operator overloading12Identification of classes and their relationships13Composition and aggregation14Inheritance15Multiple inheritance16Polymorphism17Abstract classes and interfaces18Generic programming concepts19Function & class templates20Standard template library21Object streams22Data and object serialization using object streams23Exception handling
    8 min read
    Topic 23 of 23
    Topic Study Note Illustration
    23

    Exception handling

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming