Tuesday, February 20, 2024

EXCEPTION HANDLING IN C++

Exception handling in C++

  • WHAT IS EXCEPTION HANDLING 
  • ADVANTAGES 
  • C++ EXCEPTION CLASSES
  • TRY/CATCH

Exception handling in C++ is the process of handling runtime errors. We implement exception handling to maintain the normal flow of the application even after runtime errors.

In C++, an exception is an event or object thrown at runtime. All exceptions derive from the std::exception class. This is a runtime error that can be handled. If we don't handle the exception, it prints the exception message and stops the program.

 Advantage: -This maintains the normal flow of the application. In this case, the rest of the code is also executed after the exception.

 C++ exception classes

In the C++ standard, exceptions are defined as <exception> in a class that we can use in our programs. The parent-child class hierarchy arrangement is shown below:

Now let’s see C++ common exception classes

 

Exception

Description

std::exception

It is an exception and parent class of all standard C++ exceptions.

std::logic_failure

It is an exception that can be detected by reading a code.

std::runtime_error

It is an exception that cannot be detected by reading a code.

std::bad_exception

It is used to handle unexpected exceptions in a C++ program.

std::bad_cast

This exception is generally thrown by dynamic_cast.

std::bad_typeid

This exception is generally thrown by typeid.

std::bad_alloc

This exception is generally thrown by new

 

There are three types of exception-handling keywords: -

    1)      Try

    2)      Catch

    3)      Throw

 Try/catch 

In C++ programming, exception handling is done using a try/catch statement. The C++ try block is used to place code that might throw an exception. A Catch block is used to handle the exception.

 

Let us understand this by a simple C++ program

First, we try it without try/catch

 

#include <iostream>  

using namespace std;  

float division(int x, int y) {  

   return (x/y);  

}  

int main () {  

   int i = 50;  

   int j = 0;  

   float k = 0;  

      k = division(i, j);  

      cout << k << endl;  

   return 0;  

}  


 

Output

Floating point exception (core dumped)

 

Now let us try it with try/catch

 

#include <iostream>  

using namespace std;  

float division(int x, int y) {  

   if( y == 0 ) {  

      throw "Attempted to divide by zero!";  

   }  

   return (x/y);  

}  

int main () {  

   int i = 25;  

   int j = 0;  

   float k = 0;  

   try {  

      k = division(i, j);  

      cout << k << endl;  

   }catch (const char* e) {  

      cerr << e << endl;  

   }  

   return 0;  

}  

Output

Attempt to divide by zero 

No comments:

Post a Comment

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular