Open In App

C++ Program to Handle the Checked Exceptions

Improve
Improve
Like Article
Like
Save
Share
Report

An Exception is a run-time error, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. For example, Lack of Memory, Lack of Disk Space, Dividing by zero, etc.

Types of Exceptions

There are two types of Exceptions, Built-in Exceptions, and User-Defined Exceptions. Built-in Exceptions can be divided into 2 main categories:

  1. Checked Exception: These are the compile-time exceptions because these exceptions are checked by the compiler at the compile-time. The compile ensures whether the programmer handles the exception or not. 
  2. Unchecked Exception: The compiler will not check the unchecked exceptions at compile time. It occurs when the sure inputs bad input during interaction with the program.

What are Checked Exceptions?

The exception is checked by the compiler for smooth execution of the program at runtime.

  • Checked exceptions commonly occur exception. So, the compiler takes very much care about these exceptions.
  • It is possible that a method declares that it can throw an exception, but actually it does not. Still, the caller has to deal with it. 
  • The checked exception declaration has a domino effect. Any methods that will use the previous method will also have to handle the checked exception.

The Exception class is the base class from which exceptions inherit. For example, the InvalidCastException class hierarchy is as follows: Object. Exception. SystemException.

Why exceptions aren’t checked by the compiler in C++?

C++ provides a syntax for checked exceptions.

Example: 

void G() throw(Exception);

void f() throw();

Exceptions are not checked by the compiler in C++ for 3 reasons:

1. C++ exception specifications inhibit optimization: With the exception possibly of throw(), compilers insert extra code to check that when you throw an exception, it matches the exception specification of functions during a stack unwind. Way to make your program slower.

2. C++ exception specifications are not compiler-enforced: As far as your compiler is concerned, the following is syntactically correct:

void AStupidFunction() throw()
{
   throw 42;
}

If the exception specification is violated then the program terminates the execution.

3. C++ exception specifications are part of a function’s signature: If you have a base class with a virtual function and try to override it, the exception specifications must match exactly. So, you’d better plan ahead, and it’s still a pain.

struct A
{
   virtual int value() const throw() 
   {
      return 10;
   }
}

struct B : public A
{
   // ERROR!
   virtual int value() const 
   {
       return functionThatCanThrow();
   } 
}

Exception specifications give you these problems, and the gain for using them is minimal. In contrast, if you avoid exception specifications altogether, coding is easier and you avoid this stuff.

Exception Handling

Exception Handling is a process to handle runtime errors. We perform exception handling. So, the normal flow of the program can be maintained even after runtime errors. It is designed to handle synchronous exceptions only in the program. C++ exception handling is built upon three keywords: try, catch, and throw.

1. try Block: A block of code containing other code that could potentially have an exception.

Syntax:

try{
  statement1;
  statement2;
}

2. catch: This handles the exception with some sort of solution.

Syntax:

try{
  statement1;
  statement2;
}

catch (argument)
{
   // Action
  statement3;
}

3. throw: This statement can be added anywhere after some kind of exception condition.

throw(excep);

throw excep;

throw; // re-throw

How Do you Handle Exceptions?

Exception Handling is a process to handle runtime errors. We perform exception handling. So, the normal flow of the program can be maintained even after runtime errors. It is designed to handle synchronous exceptions only in the program.

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions

Below is the C++ program to handle checked exceptions:

C++




// C++ program to handle
// exceptions
#include <iostream>
using namespace std;
 
int division(int a, int b)
{
  // Checking if the denominator
  // is 0 or not.
  if (b == 0)
  {
    // If the denominator is 0, then
    // we must throw an exception
    throw "Division by zero!";
  }
     
  // If there is no exception, then
  // we are returning the answer.
  return int(a / b);
}
 
// Driver code
int main()
{
  int x = 50;
  int y = 0;
  int answer = 0;
     
  /*
    Using a try catch block because in division,
    the denominator can be 0.
    So, we must handle the 0 division inside try block.
  */
  try
  {
    answer = division(x, y);
    cout << " Output: " << answer << endl;
  }
     
  // Printing the thrown exception from
  // the function
  catch (const char *errorMessage)
  {
    cout << errorMessage << endl;
  }
   
  return 0;
}


Output:

Division by zero!


Last Updated : 19 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads