C++ Program to Handle the Unchecked Exceptions
Last Updated :
02 Aug, 2022
Exceptions are run-time errors or abnormal conditions that a program may encounter during execution.
Examples:
- Division by zero
- Access to an array out of its bounds
- Running out of memory
- Running out of disk space
Types of Exceptions:
- Synchronous Exceptions: The exceptions which occur during the program execution due to some fault in the input data. For example, Errors such as overflow, and division by zero.
- Asynchronous Exceptions: The exceptions caused by events or faults unrelated (extended) to the program and beyond the control of the program. For example Keyboard failures, and hardware disk failures.
The exception handling in C++ is designed to handle only synchronous exceptions in a program. The goal of exception handling is to create a routine that checks and sends an exceptional condition in order to execute suitable code. The procedure needs to carry out the following responsibilities:
- Detect the problem(Hit the exception)
- Tells about error detection(throw the exception)
- Receive error information(Catch the exception)
- Take corrective action(Handle the exception)
The keywords try, throw, and catch. The keyword try is used to preface a block of code which may result in exceptions.
Syntax of try statement:
try{
statement1;
statement2;
}
When an exception is found, it is thrown using a throw statement in the try block.
Syntax of the throw statement
throw(excep);
throw excep;
throw;// re-throwing of an exception
A catch block is defined by the keyword 'catch' the exception and handles it accordingly. The catch block that catches an exception must immediately follow the try block of the exception.
Syntax of catch statement:
try{
statement1;
statement2;
}
catch (argument)
{
statement3;// action to be taken
}
When an exception is found, the execution of the catch block starts. The catch statement may or may not contains an argument of exception type, it is optional. When an argument is declared in the catch, the argument can be used in the catch block. After the execution of the catch block, the lines inside the blocks are executed. In case no exception is found, the catch block is ignored and if a mismatch is found, the program is finished.
C++ Program to illustrate Division by Zero Exception
C++
// C++ program to illustrate
// division by zero exception
#include <iostream>
using namespace std;
int main()
{
int Gfg1 = 9, Gfg2 = 0;
// try block starts here
try {
if (Gfg2 != 0)
cout << Gfg1 / Gfg2;
else
throw Gfg2; // throwing if Gfg2 is zero
}
// catch block starts here
catch (int i) {
/// if b is zero means division is done 0 hence
// thrown from try block and catch
cout << "Division by zero: " << i << endl;
}
return 0;
}
Output:
Division by zero: 0
C++ Program to illustrate Array Index Out of Bounds Exception
C++
// C++ program to demonstrate
// array index out of bounds
// exception
#include <iostream>
using namespace std;
int main()
{
// initialize an array of
// size 5 with numbers from 1 to
// 5
int a[5] = { 1, 2, 3, 4, 5 }, i;
// try block starts here
try {
i = 0; // initialize i with 0
// loop for printing value of array till its
// size 5
while (1) {
if (i != 5) {
cout << a[i] << endl;
i++;
}
// if i go beyond 5 then throw exception
else
throw i;
}
}
// catch the exception
catch (int i) {
cout << "Array Index out of Bounds Exception: " << i
<< endl;
}
return 0;
}
Output:
1
2
3
4
5
Array Index out of Bounds Exception: 5
C++ Program to Throw Multiple Exceptions and Define Multiple Catch Statements
C++
// C++ program to throw multiple
// exceptions and define
// multiple catch statement
#include <iostream>
using namespace std;
// function to check if number is
// positive, negative or zero
void num(int k)
{
try {
if (k == 0)
throw k; // throwing int value
else if (k > 0)
throw 'P'; // throwing char value
else if (k < 0)
throw 1.0; // throwing double value
cout << "*** end of try block ***\n";
}
// catching char value
catch (char g) {
cout << "Caught a positive value \n";
}
// catching integer value
catch (int j) {
cout << "caught an null value \n";
}
// catching double value
catch (double f) {
cout << "Caught a Negative value \n";
}
cout << "*** end of try catch ***\n \n";
}
int main()
{
cout << "Demo of Multiple catches" << endl;
num(0); // function call for zero
num(5); // function call for positive
num(-1); // function call for negative
return 0;
}
Output:
Demo of Multiple catches
caught an null value
*** end of try catch ***
Caught a positive value
*** end of try catch ***
Caught a Negative value
*** end of try catch ***
Similar Reads
C++ Program to Handle the Checked Exceptions 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-
5 min read
C++ Program to Show Runtime Exceptions A runtime error occurs while the program is running. Because this is not a compilation error, the compilation will be completed successfully. Here, we will learn how to handle runtime exceptions in C++. There are 5 types of runtime exceptions discussed here: Division by zero. Segmentation faults. La
3 min read
C++ Program to Show Unreachable Code Error Unreachable code is a compile-time error in languages like C++, Java, and C or Unreachable code error occurs when the code canât be compiled; but why it is just a warning in C++ & C ? Warnings are a way that the compiler indicates that the particular mentioned thing might become an error in futu
1 min read
How to Use the ignore() Function in C++? In C++, the ignore() function is a part of std::basic_istream that is used to discard the characters in the stream until the given delimiter(including it) is reached and then extracts the left-out remainder. In this article, we will learn how to use the ignore() function in C++. C++ ignore() Functio
2 min read
How to Throw an Exception in C++? In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are objects that represent an error that occurs during the execution of a program. In this article, we will learn how to throw an exception in C++. Throw a C++ ExceptionThrowing an exception means sendin
2 min read
Exception Handling using classes in C++ In C++, unexpected issues may occur during program execution such as attempting to divide by zero, accessing a non-existent file or using invalid data. These issues are called exceptions. These exceptions must be handled to avoid abnormal termination of the program.C++ provides try-catch block to ha
5 min read
Exception Header in C++ With Examples C++ provides a list of standard exceptions defined in header <exception> in namespace std where "exception" is the base class for all standard exceptions. All exceptions like bad_alloc, bad_cast, runtime_error, etc generated by the standard library inherit from std::exception. Therefore, all s
5 min read
How to Throw and Catch Exceptions in C++? In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are unusual conditions that occur at runtime. In this article, we will learn how to throw and catch exceptions in C++. Throw and Catch Exceptions in C++In C++ exceptions can be "thrown" when an error occ
2 min read
How to Use cin.fail() Method in C++? In C++, the cin.fail() method is a part of <iostream> library that is used to check whether the previous input operation has succeeded or not by validating the user input. In this article, we will learn how to use cin.fail() method in C++. Example: Input: Enter an integer: aOutput: Invalid Inp
2 min read
How to Catch All Exceptions in C++? In C++, exceptions are objects that indicate you have an error in your program. They are handled by the try-catch block in C++. In this article, we will learn how to catch all the exceptions in C++. Catching All Exceptions in C++To catch all kinds of exceptions in our catch block in C++, we can defi
2 min read