Exception-Handling-in-CPP
Exception-Handling-in-CPP
Topperworld.in
Exception Handling
Run Time Errors - They are also known as exceptions. An exception caught
during run time creates serious issues.
©Topperworld
C++ Programming
o try
o catch
o throw
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
The throw keyword throws an exception when a problem is detected,
which lets us create a custom error.
The catch statement allows you to define a block of code to be executed
if an error occurs in the try block.
Syntax:
try {
// Block of code to try
throw exception;
}
catch () {
// Block of code to handle errors
}
Let's take a simple example to understand the usage of try, catch and throw.
Below program compiles successfully but the program fails at runtime, leading
to an exception.
#include <iostream>#include<conio.h>
int main()
©Topperworld
C++ Programming
int a=10,b=0,c;
c=a/b;
return 0;
The above program will not run, and will show runtime error on screen, because
we are trying to divide a number with 0, which is not possible.
How to handle this situation? We can handle such situations using exception
handling and can inform the user that you cannot divide a number by zero, by
displaying a message.
Now we will update the above program and include exception handling in it.
#include <iostream>
#include<conio.h>
int main()
try
©Topperworld
C++ Programming
if(b == 0)
c = a/b;
cout<<ex;
return 0;
Output:
©Topperworld
C++ Programming
Doing so, the user will never know that our program failed at runtime, he/she
will only see the message "Division by zero not possible".
Exception Classes
In C++ standard exceptions are defined in <exception> class that we can use
inside our programs. The arrangement of parent-child class hierarchy is shown
below:
All the exception classes in C++ are derived from std::exception class. Let's see
the list of C++ common exception classes.
Exception Description
©Topperworld
C++ Programming
It maintains the normal flow of the application. In such case, rest of the
code is executed even after exception.
©Topperworld