WEB DEVELOPER SITE
PYTHONPHPJAVA
 

C++ Exceptions


Exceptions

Problems that occur during program execution are called exceptions.

C++ exceptions are responses to anomalies that arise while the program is running, such as an attempt to divide by zero.

Exceptions are used to handle error in the program

Throwing Exceptions

Throwing exception have three keywords such as try, catch, and throw.
throw is used to throw an exception when a problem shows up. int FatherAge = 30; int DaughterAge = 46; if (DaughterAge > FatherAge) { throw "Wrong age values"; }

DaughterAge and FatherAge, and throws an exception if DughterAge is found to be the greater of the two.

Catching Exceptions

try block identifies a block of code that will activate specific exceptions.



It's followed by one or more catch blocks. The catch keyword represents a block of code that executes when a particular exception is thrown.

try {
  int Age = 14;
  int daughterAge = 58;
  if (daughterAge > fatherAge) {
   throw 99;
  }
} 
catch (int x) {
  cout<<"Wrong age values - Error "<<x;
}

//Outputs "Wrong age values - Error 96"

Exception Handling

Exception handling is particularly useful when dealing with user input.

#include <iostream>
using namespace std;

int main() {
    int t1;
    cout <<"get rank number:";
    cin >> t1;
    
    int t2;
    cout <<"get rank number:";
    cin >> t2;
    
    cout <<"Result:"<
In case of 0 the program crashes, so we need to handle that input.

we need to handle the thrown exception using a try/catch block
#include <iostream>
using namespace std;

int main() {
    try {
        int t1;
        cout <<"Get rank number:";
        cin >> t1;
        
        int t2;
        cout <<"Get rank number:";
        cin >> t2;
        
        if(t2 == 0) {
            throw 0;
        }
        
        cout <<"Result:"<

To accomplish this, add an ellipsis (...) between the parentheses of catch

try {
  // code
} catch(...) {
  // code to handle exceptions
}