C++ Program To Show Runtime Exceptions

In this example, we will discuss a C++ program to show runtime exceptions. But before discussing the implementation the runtime exceptions, we must know about the exceptions or exception handling in C++.

Exceptions in C++:

An exception in C++ is a problem that occurs while a program is running. The program can throw exceptions, which alerts that an error condition has been identified when something goes wrong. Specifically, runtime exceptions are exceptions that arise while the program is running, as opposed to compile-time errors, which are faults that the compiler finds.

C++ Exception Handling :

Programmers can gracefully manage runtime failures with the built-in exception handling capabilities in C++. In C++, addressing exceptions requires three primary keywords:

try:-

  • A code segment where exceptions are permitted .
  • An exception is detected in the code inside the try block.

throw:-

  • Applied to explicitly throw an exception.
  • The program can throw an exception object of a particular type upon detecting an issue.

catch:-

  • catch is the code block that is used to manage exceptions .
  • A matching catch block is triggered if an exception arises within the try block.
  • Example programs to demonstrate runtime Exceptions in C++:

    1. Divide by zero exception:

    Example
    
    #include<iostream>
    int main() 
    {
        int numerator = 10;
        int denominator = 0;
        try {
            if (denominator == 0) {
                throw "Divide by zero exception";
            }
            int result = numerator / denominator;
            std::cout << "Result: " << result << std::endl;
        } catch (const char* msg) {
            std::cerr << "Error: " << msg << std::endl;
        }
        return 0;
    }
    

Output:

Explanation:

The goal of this program is to divide an integer by zero. Hence, dividing a number with zero is not calculatable in maths. If we try to calculate, it will throw a runtime exception. Here, the try-catch block is used to catch an exception.

2. Array Out of Bounds Exception:

Example

#include<iostream>
#include <vector> 
 int main() 
{ 	std::vector<int> v = { 8,3,6,1,9 }; 
	 	v[0] = 12; // arr is now: { 12, 3, 6, 1, 9 }
 	 	//v[5] = 19; // Undefined behavior: index is out of bounds 
	             // (No bounds checking was done here) 	
try 	
{ 		
v.at(5) = 19; 
// use at() function to access element 	
} 	
catch (...) 	
{ 		
std::cout << "Out-of-bounds exception captured!\n"; 
	} 
	 	 	return 0; 
}
}

Output:

Explanation:

In the above program, we tried to access an element from a vector that is out of bounds index. If the index of an element that we want to access is outside of the bound value, at method is used and it will raise an exception std::outofrange. Try-catch block should be used to catch the exception.

3. Null Pointer Exception:

Example

#include<iostream>
int main() {
    int* ptr = nullptr;

    if (ptr == nullptr) {
        std::cerr << "Error: Null pointer exception" << std::endl;
        return 1; // Return an error code indicating failure
    }
    std::cout << "Value: " << *ptr << std::endl; // Attempting to dereference a null pointer
    return 0;
}

Output:

Explanation:

In this program, we try to dereference a null pointer (ptr). A runtime exception is frequently raised when a null pointer is dereferencing, which results in undefined behavior. Using a try-catch block, we manage this exception by printing an error message.

4. File I/O Exception:

Example

#include<iostream>
#include <fstream>
int main() {
    try {
        std::ifstream file("nonexistent_file.txt");
        if (!file) {
            throw std::runtime_error("File not found");
        }
        int value;
        file >> value;
        std::cout << "Value: " << value << std::endl;
        file.close();
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

Output:

Explanation:

In this program, we are attempting to open an invalid file. A runtime exception will occur if we try to open a nonexistent file. Using a try-catch block, we manage this exception by printing an error message.

5. Vector Iterator Exception:

Example

#include<iostream>
#include<vector>
#include<stdexcept>
int main()
{
std::vector<int>v={9,8,7,6,5};
try
{
for(int i=0;i<v.size();i++)
{
cout<<v.at(i)<<endl;
}
catch(const std::out_of_range& e)
{
cerr<<?Error?<<e.what()<<endl;
}
return 0;
}

Output:

Explanation:

Using iterators, we try to iterate over a vector in this program. But we mistakenly increment the end iterator in the loop condition, which could result in undefined behavior and a runtime exception. Any exception derived from std::exception is caught by the program, which outputs an error message.

6. String Index Out of Bounds Exception:

Example

#include<iostream>
#include<string>
#include<stdexcept>
int main()
{
std::string s =?Hello,JTP?;
try
{
char c=str.at(25);
cout<<?char at index 25:?<<ch<<endl;
}
catch(const std::out_of_range& e)
{
cerr<<?error?<<e.what()<<endl;
}
return 0;
}

Output:

Explanation:

This program initializes a string str with "Hello, World!". After that, we try to access the value at index 20 using the method at. Hence, if the string length is less than 20, this will result std::outofrange error.

Input Required

This code uses input(). Please provide values below: