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++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read