Tuesday, August 8, 2023
HomeArtificial IntelligenceException Dealing with in C++ | What's Exception Dealing with in C++

Exception Dealing with in C++ | What’s Exception Dealing with in C++


Exception dealing with in C++ is a specific situation for builders to deal with. In programming, committing errors that immediate uncommon situations referred to as errors is regular. All in all, these errors are of three varieties:

  1. Syntax Error
  2. Logical Error 
  3. Runtime Error

What’s Exception Dealing with in C++? 

Exception dealing with in C++ is a mechanism that permits a program to take care of runtime errors and distinctive conditions in a structured and managed method. In C++, exceptions are used to deal with errors that happen throughout the execution of a program, comparable to division by zero, accessing invalid reminiscence, or file I/O errors.

The essential concept behind exception dealing with is to separate the conventional circulate of program execution from error-handling code. As an alternative of terminating this system abruptly when an error happens, C++ supplies a technique to “throw” an exception, representing the error or distinctive situation. The thrown exception is then caught by acceptable “catch” blocks, the place this system can deal with the error gracefully.

Right here’s a primary define of how exception dealing with works in C++:

  1. Throwing an Exception:
    When a essential error happens throughout program execution, you should utilize the throw assertion to boost an exception. It often takes an object as an argument, which serves because the illustration of the error.
#embrace <iostream>

void someFunction(int worth) {
    if (worth == 0)
        throw std::runtime_error("Error: Division by zero!");
    // ... different code ...
}
  1. Catching an Exception:
    To catch an exception, you employ a attempt block. The code which may elevate an exception is positioned contained in the attempt block. If an exception is thrown inside the attempt block, this system will instantly bounce to the corresponding catch block.
int foremost() {
    attempt {
        int x = 10;
        int y = 0;
        someFunction(x / y);
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    // ... different code ...
    return 0;
}
  1. Dealing with the Exception:
    The catch block handles the caught exception. It specifies the kind of exception it might catch in parentheses, adopted by a block of code that handles the distinctive situation.
  2. A number of Catch Blocks:
    You’ll be able to have a number of catch blocks to deal with several types of exceptions. The primary catch block that matches the thrown exception’s kind will probably be executed, and the others will probably be skipped.
attempt {
    // code which will throw exceptions
} catch (const SomeExceptionType& e) {
    // deal with SomeExceptionType
} catch (const AnotherExceptionType& e) {
    // deal with AnotherExceptionType
} catch (...) {
    // deal with some other exception that isn't caught by earlier catch blocks
}
  1. Exception Security:
    Exception security refers back to the idea of guaranteeing {that a} program’s state stays constant even when an exception is thrown. Writing exception-safe code is important to forestall useful resource leaks and keep information integrity.

By utilizing exception dealing with, you may make your C++ packages extra sturdy and maintainable, as they supply a technique to deal with errors in a managed method, quite than having this system terminate abruptly on encountering a problem.

When no exception situation occurs, the code will execute ordinarily. The handlers will probably be disregarded.

A easy instance to grasp Distinctive dealing with in C++

#embrace <iostream>

int foremost() {
    attempt {
        // Code which will throw an exception
        int numerator = 10;
        int denominator = 0;
        int outcome = numerator / denominator;

        std::cout << "End result: " << outcome << std::endl;
    }
    catch (const std::exception& e) {
        std::cout << "Exception occurred: " << e.what() << std::endl;
    }

    return 0;
}

On this instance, the division operation numerator/denominator might throw a std::exception when the denominator is zero. The attempt block accommodates the code which may throw an exception, and the catch block catches the exception and handles it appropriately.

Additionally, now you’ll be able to be taught Exception Dealing with in C – A Free On-line Course in Hindi

Why Exception Dealing with? 

Exception dealing with is a vital idea in programming that permits builders to take care of surprising or distinctive conditions which will happen throughout the execution of a program. These distinctive conditions are also known as “exceptions.” Listed here are some the explanation why exception dealing with is necessary:

  1. Error Administration: When a program encounters an error or surprising situation, with out exception dealing with, it would crash or produce incorrect outcomes. Exception dealing with supplies a structured technique to take care of errors and permits builders to deal with them gracefully.
  2. Robustness: Exception dealing with enhances the robustness of the software program. By catching and dealing with exceptions, builders can forestall your complete program from terminating abruptly and supply customers with significant error messages, making the software program extra user-friendly.
  3. Separation of Considerations: Exception dealing with clearly separates regular program circulate and error working code. This separation makes the code simpler to learn, perceive, and keep.
  4. Debugging: Exception dealing with aids in debugging the code. When an exception is thrown, this system can log particulars in regards to the error, which helps builders determine and repair the problem’s root trigger.
  5. Sleek Restoration: In sure circumstances, packages can recuperate from exceptions and proceed execution as a substitute of crashing. For instance, an online server can catch an exception attributable to a client-side error and reply with an acceptable HTTP error code as a substitute of shutting down.
  6. Program Stability: By dealing with exceptions appropriately, builders can be certain that this system stays steady and dependable even when dealing with surprising situations or inputs.
  7. Fail-Protected Operations: Exception dealing with is particularly necessary when coping with essential operations like file I/O, community communication, or database transactions. Dealing with exceptions accurately makes it attainable to roll again transactions or carry out different needed cleanup duties to take care of information integrity.
  8. Modularity: Exception dealing with permits for modular design and promotes code reusability. Features or strategies can throw exceptions, and the calling code can catch and deal with them accordingly.

Primary Key phrases in Exception Dealing with: 

Exception Dealing with in C++ falls round these three key phrases: 

What’s attempt throw catch in c++?

In C++, attempt, throw, and catch are key phrases used for exception dealing with. Exception dealing with permits builders to deal with errors or distinctive conditions gracefully and supply a structured technique to handle surprising situations throughout the execution of a program.

Right here’s a quick rationalization of every key phrase:

  1. attempt: The code which may elevate an exception is included inside the attempt block. A number of catch blocks come after it. This system appears to be like for a catch block that matches the attempt block when an exception is thrown inside the attempt block so as to deal with the exception.
  2. throw: To explicitly elevate or throw an exception, use the throw key phrase. Within the attempt block, it’s incessantly employed when an distinctive circumstance arises. The management exits the attempt block when the throw assertion is met so as to find an acceptable catch block to deal with the exception.
  3. catch: The catch block follows the attempt block and is used to catch and deal with exceptions. It accommodates code that executes when a particular kind of exception is thrown inside the related attempt block. A number of catch blocks can be utilized for various exception sorts.
attempt {
    // Code which may throw an exception
    // If an exception is thrown, management jumps to the corresponding catch block
} catch (ExceptionType1 e) {
    // Code to deal with ExceptionType1
} catch (ExceptionType2 e) {
    // Code to deal with ExceptionType2
} catch (...) {
    // Catch-all block to deal with some other unhandled exceptions (optionally available)
}

How try-catch in c++ works?

In C++, exception dealing with is finished utilizing the try-catch mechanism. It means that you can catch and deal with exceptions that happen throughout the execution of your program. The attempt block accommodates the code which may throw an exception, and it handles the exception if it happens. Right here’s the way it works:

  1. The code which may throw an exception is enclosed inside a attempt block. If an exception happens inside this block, the execution of the code inside the attempt block is instantly stopped, and this system appears to be like for an identical catch block to deal with the exception.
  2. After an exception is thrown, this system searches for an identical catch block. An identical catch block is one that may deal with the precise kind of exception that was thrown. If an identical catch block is discovered, the code inside that block is executed.
  3. If no matching catch block is discovered inside the present scope, this system strikes up the decision stack, looking for an acceptable catch block within the calling features. This course of continues till an identical catch block is discovered or till this system reaches the highest degree of this system (i.e., foremost() operate).
  4. As soon as an identical catch block is discovered, the code inside that block is executed, and this system continues executing from the purpose instantly after the try-catch block.

Right here’s an instance as an example the utilization of try-catch:

#embrace <iostream>

int foremost() {
    attempt {
        // Code which may throw an exception
        int num1, num2;
        std::cout << "Enter two numbers: ";
        std::cin >> num1 >> num2;

        if (num2 == 0) {
            throw std::runtime_error("Divide by zero exception");
        }

        int outcome = num1 / num2;
        std::cout << "End result: " << outcome << std::endl;
    }
    catch (const std::exception& e) {
        // Exception dealing with code
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Example1: A number of Code Block

#embrace <iostream>

int foremost() {
    attempt {
        // Code which will throw an exception
        int numerator = 10;
        int denominator = 0;
        int outcome = numerator / denominator;

        std::cout << "End result: " << outcome << std::endl;
    }
    catch (const std::runtime_error& e) {
        std::cout << "Runtime error occurred: " << e.what() << std::endl;
    }
    catch (const std::exception& e) {
        std::cout << "Exception occurred: " << e.what() << std::endl;
    }

    return 0;
}

Right here, we now have added a further catch block to deal with a particular kind of exception, std::runtime_error, earlier than catching the extra common std::exception. The particular exception sorts needs to be caught earlier than the extra common ones.

Example2: Throwing a Customized Exception

#embrace <iostream>
#embrace <stdexcept>

void checkAge(int age) {
    if (age < 0) {
        throw std::invalid_argument("Age can't be damaging.");
    }
    else if (age < 18) {
        throw std::out_of_range("You should be at the least 18 years previous.");
    }
    else {
        std::cout << "Entry granted." << std::endl;
    }
}

int foremost() {
    attempt {
        int userAge = 15;
        checkAge(userAge);
    }
    catch (const std::exception& e) {
        std::cout << "Exception occurred: " << e.what() << std::endl;
    }

    return 0;
}

On this instance, the checkAge the operate throws customized exceptions, std::invalid_argument and std::out_of_range, based mostly on the age worth offered. The attempt block calls the checkAge operate, and if an exception is thrown, it’s caught and dealt with within the catch block.

use try-catch in c++?

Attempt-catch is a crucial key phrase whereas performing distinctive situations.
Within the Attempt block, the “throw” key phrase throws an exception when the code detects an issue, which lets us create a customized error.
Now “catch” key phrase comes into an image i.e. “catch” key phrase means that you can outline a block of code to be executed if an error happens within the attempt block.

How do you catch exceptions in C++?

To catch exceptions, part of the code is stored beneath inspection. That is completed by closing that a part of the code in a try-block. When an distinctive circumstance arises inside that block, an exception is thrown and an exception handler takes management over this system.

throw an exception in c++?

In C++, you’ll be able to throw an exception utilizing the throw key phrase. Exceptions are a technique to deal with error situations or distinctive conditions in your code which will disrupt the conventional circulate of execution. When an exception is thrown, this system will cease executing the present block of code and begin looking for an acceptable exception handler (catch block) to deal with the exception.

To throw an exception in C++, you sometimes observe these steps:

Outline a customized exception class (optionally available):
You’ll be able to create your personal customized exception class by inheriting from the usual std::exception class or any of its derived courses. This step is optionally available, as you may as well use the usual exception courses offered by the C++ Commonplace Library.

Throw the exception:
Use the throw key phrase adopted by the exception object you wish to throw. When you’ve got created a customized exception class, you’ll be able to instantiate an object of that class and cross it to the throw assertion.

Catch the exception (optionally available):
To deal with the thrown exception, it is advisable to enclose the code which will throw an exception inside a try-catch block. The catch block will catch the thrown exception and help you deal with it gracefully.

Right here’s an instance of the way to throw and catch an exception in C++:

#embrace <iostream>

// Customized exception class (optionally available)
class MyException : public std::exception {
public:
    digital const char* what() const noexcept override {
        return "My customized exception occurred!";
    }
};

int foremost() {
    attempt {
        int age;
        std::cout << "Enter your age: ";
        std::cin >> age;

        if (age < 0) {
            // Throw a customized exception
            throw MyException();
        }

        // Different code which will throw exceptions
        // ...

    } catch (const MyException& ex) {
        std::cout << "Caught customized exception: " << ex.what() << std::endl;
    } catch (const std::exception& ex) {
        // Catch different exceptions derived from std::exception
        std::cout << "Caught commonplace exception: " << ex.what() << std::endl;
    } catch (...) {
        // Catch some other unhandled exceptions (not really helpful, however could be helpful for debugging)
        std::cout << "Caught unknown exception." << std::endl;
    }

    return 0;
}

On this instance, if the consumer enters a damaging age, the MyException object will probably be thrown, and will probably be caught by the corresponding catch block.

C++ Commonplace Exceptions

In C++, you’ll be able to create your personal user-defined exceptions to deal with particular error situations in your code. Person-defined exceptions help you outline customized exception sorts that inherit from the usual C++ std::exception class or any of its derived courses. This lets you throw and catch particular exception sorts that characterize completely different error conditions.

Right here’s a step-by-step information on the way to outline and use user-defined exceptions in C++:

Step 1: Outline your customized exception class

#embrace <exception>
#embrace <string>

class MyException : public std::exception {
public:
    MyException(const std::string& message) : message_(message) {}

    // Override the what() technique to supply error description
    const char* what() const noexcept override {
        return message_.c_str();
    }

non-public:
    std::string message_;
};

Step 2: Throw the user-defined exception
You’ll be able to throw the customized exception in your code when a particular error situation is encountered. For instance:

#embrace <iostream>

double divideNumbers(double numerator, double denominator) {
    if (denominator == 0) {
        throw MyException("Division by zero shouldn't be allowed.");
    }
    return numerator / denominator;
}

int foremost() {
    attempt {
        double outcome = divideNumbers(10.0, 0.0);
        std::cout << "End result: " << outcome << std::endl;
    } catch (const MyException& ex) {
        std::cout << "Error: " << ex.what() << std::endl;
    }

    return 0;
}

On this instance, we outlined a customized MyException class and used it to throw an exception when dividing by zero within the divideNumbers operate. Within the foremost operate, we catch the exception and deal with it by printing the error message.

Step 3: Deal with the user-defined exception
When an exception is thrown, you’ll be able to catch it utilizing a attempt block and deal with it with a corresponding catch block. On this instance, we catch MyException and print its error message utilizing the what() technique.

Person-defined exceptions are useful for offering significant error messages and dealing with particular error situations in your code. You’ll be able to create a number of customized exception courses to characterize several types of errors, which permits for higher group and readability in your exception dealing with.

What’s C++ Commonplace Exceptions?

C++ commonplace exceptions present a listing of ordinary exceptions outlined in <exception> which we are able to use in our packages.
These exceptions are organized in a parent-child class hierarchy:

Person-Outlined Exceptions 

In C++, you’ll be able to create your personal user-defined exceptions to deal with particular error situations in your code. Person-defined exceptions help you outline customized exception sorts that inherit from the usual C++ std::exception class or any of its derived courses. This lets you throw and catch particular exception sorts that characterize completely different error conditions.

Right here’s a step-by-step information on the way to outline and use user-defined exceptions in C++:

Step 1: Outline your customized exception class

#embrace <exception>
#embrace <string>

class MyException : public std::exception {
public:
    MyException(const std::string& message) : message_(message) {}

    // Override the what() technique to supply error description
    const char* what() const noexcept override {
        return message_.c_str();
    }

non-public:
    std::string message_;
};

Step 2: Throw the user-defined exception
You’ll be able to throw the customized exception in your code when encountering a particular error situation. For instance:

#embrace <iostream>

double divideNumbers(double numerator, double denominator) {
    if (denominator == 0) {
        throw MyException("Division by zero shouldn't be allowed.");
    }
    return numerator / denominator;
}

int foremost() {
    attempt {
        double outcome = divideNumbers(10.0, 0.0);
        std::cout << "End result: " << outcome << std::endl;
    } catch (const MyException& ex) {
        std::cout << "Error: " << ex.what() << std::endl;
    }

    return 0;
}

On this instance, we outlined a customized MyException class and used it to throw an exception when dividing by zero within the divideNumbers operate. Within the foremost operate, we catch the exception and deal with it by printing the error message.

Step 3: Deal with the user-defined exception
When an exception is thrown, you’ll be able to catch it utilizing a attempt block and deal with it with a corresponding catch block. On this instance, we catch MyException and print its error message utilizing the what() technique.

Person-defined exceptions are useful for offering significant error messages and dealing with particular error situations in your code. You’ll be able to create a number of customized exception courses to characterize several types of errors, which permits for higher group and readability in your exception dealing with.

This brings us to the top of the weblog on Exception Dealing with in C++. Hope this lets you up-skill your C++ abilities. To be taught extra about programming and different associated ideas, try the programs on Nice Studying Academy

Additionally, in case you are getting ready for Interviews, try these Interview Questions for C++ to ace it like a professional

Seize the alternatives that await you thru our dynamic vary of free programs. Whether or not you’re excited by Cybersecurity, Administration, Cloud Computing, IT, or Software program, we provide a broad spectrum of industry-specific domains. Acquire the important abilities and experience to thrive in your chosen subject and unleash your full potential.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments