Back to: C++ Tutorials For Beginners and Professionals
Exception Handling in C++ with Examples:
In this article, I am going to discuss Exception Handling in C++ with Examples. Please read our previous article where we discussed Nested or Inner Classes in C++ with Example. Exception handling in C++ provides you with a way of handling unexpected circumstances like runtime errors.
Exception Handling in C++:
Now we will discuss one of the very interesting topics in C++ or a feature of object-oriented programming and a common feature that is also present in Java, C#, and other programming languages i.e. Exception Handling. First of all, we will understand the meaning of the exception. See there are 3 types of errors that are occurred in programming, they are as follows:
- Syntax Error
- Logical Error
- Runtime Error
Syntax Error:
What is a Syntax error? While typing the program, if the programmer mistypes something or did not write something properly then there is an error known as Syntax Error. So, who will identify this error? The compiler will identify this error.
For example, the variable is not declared but used in the program or variable is not initialized but used in the program or semicolon is missing or if statement is not given properly or a conditional statement is not given properly, etc. This type of typing mistake or the lack of knowledge of the syntaxes may cause syntax errors. These types of errors are removed with the help of a compiler. These types of errors are not difficult. Once you are used to programming language syntaxes, then you can easily clear off these errors.
Logical Error:
Suppose you wanted to do something and so wrote the procedure or function or some code but when you run the program the results are different i.e. not as expected. For example, you wanted to sort elements and for the sorting element, you wrote some code but when you are running the program, it is not sorting all the elements. Some elements are missing. So, there is something wrong with your logic or the procedure that you have written.
Suppose you have used merge sort or bubble sort and you have not written the logic properly. Syntactically everything is correct but the procedure is incorrect. So, this type of error is known as a logical error. This type of error is difficult to remove because there is a problem in your logic so you have to work out the logic and then find out where it is going wrong and remove the error. In this case, the compiler will not help you.
Then is there any tool for solving this type of problem? Yes, that is a debugger. The debugger will help you to run the program line by line or statement by statement, so in each statement, you can see what is happening and wherever it is going wrong and you can catch it and you can solve that problem.
Note: The most important thing is that these two types of errors (Syntax Error And Logical Error) are faced by programmers.
Runtime Error:
A programmer develops software and then he/she will deliver it to the client that is the user of that software. Suppose you are running some business and you wanted me to develop an application for your business. So, I developed an application and that application is perfect. It is neither having any syntax errors nor having any logical errors. Then I delivered the software to you and you are a user and using that application for your business. So, the user is going to use the application and while using the application he/she must use it properly. If he/she mishandled the application then it may cause errors during the runtime of a program. It’s not development time. At the development time, as a programmer, I have faced logical and syntax errors that I have already removed. Now it is perfect. There are no errors. And you are using the program. So, at runtime, you are facing errors.
What Could Be the Cause of Error During Runtime?
Let us give you a few examples. You are supposed to enter an integer value or numeric value but you are entering a string value and for this, the program cannot continue because you are not giving proper input. So, one of the reasons for runtime errors is bad input. Second, the program that I have given you requires an internet connection but if you are not providing an internet connection then the program cannot continue. Third, the program that I have given to you needs some files on your computer system but you have deleted those files or my program is using a printer but you do not have a printer. So, these are the list of problems. These are nothing but the unavailability of resources.
All the things that are outside the program or not in the control of the program. Those are in the control of the user. So, what is the reason for the mishandling of a program? That is bad input and the problem with the resources, that are the unavailability of resources or bad resources. Like, a file is there and the program is supposed to write in that file but the file is write-protected. So, this is a bad resource.
These are the reasons for which a user may face problems. So, the user is responsible for runtime errors.
What happens in the case of runtime errors?
In case of runtime errors, the program crashes or program stops abnormally without completing its execution. Suddenly the program will stop, that’s how the runtime errors are dangerous for the user. So, who is responsible? The user is responsible because as a developer I did my job perfectly and the user is not providing proper resources or proper input so the program is failing. Now let us give you some real-life examples.
Suppose you have bought a car. A company has sold it to you and they also have trained you on how to use the functions and everything while you are purchasing a car. Then you are running the car so you have to use the car properly. You should fill the gas or petrol in time. And you should check for the engine oil from time to time and the air pressure in the tires or the condition of the tires. For all these things you are responsible as a user. If you don’t fill the gas and then you want to run the car, it will not run and suddenly it will stop. Without air pressure, if you try to run the car suddenly the car may stop because of any tire problem. If there is a lack of oil then the car may heat up and suddenly stop. So, who is responsible for this? The user is responsible. Same way because of the bad Input and unavailability of resources, the user is responsible if the program is crashing down. So, this is the idea behind types of errors.
What can we call these runtime errors?
These runtime errors are called exceptions. Why we are using the term exception? Suppose I have given you a perfect program and it will always run perfectly except in some conditions. Those conditions are giving a bad input or not providing resources. So, the program will not run in those cases. That’s why we call these exceptional cases or exceptions.
What are Exceptions?
An exception is nothing but a situation in which we get the runtime error. So, what can be done in case of these runtime errors and exceptions? Let us see in automobile engineering or other engineering streams. If there is no fuel in the car then the car will indicate that there is less amount fuel or it is in reserved condition so you must find the closest fuel station or gas station. If there is no engine oil then the car will indicate you. if you are not putting on a seat belt then the car will indicate you.
In the same way. the programs should also behave like that. If there is bad input then the program should not stop suddenly. It should ask the user that ‘this input is not proper please enter another type of Input and try again”. If there is no internet connection then the program should not stop suddenly but it should give a prompt to the user that “we found that there is no internet connection please connect to the internet and run it again”. So, the idea is the program should not terminate under such a situation but guide the user to solve the problem. Because who is there to resolve it? The programmer will not come to the client-side and check for the errors and remove them. The program itself can give a proper and meaningful message to the user so that users can remove this type of problem.
So, what is the objective of exception handling?
Giving a proper message to the user and informing them about the exact problem. And also providing him guidance to solve that problem. That’s it. This is the objective of exception handling. Now, we will see how C++ supports exception handling and how we can handle exceptions with examples.
Example to Understand Exception Handling in C++:
Let us understand how to implement exception handling with some examples. Let us first write a code without implementing exception handling in C++. Please have a look at the following example. In the below example, we are asking the user to enter two numbers and then we performing an arithmetic division operation. And in arithmetic, we know that a number cannot be divided by 0. That means in the below if we enter the second number as 0, then the arithmetic division is not possible.
#include <iostream> using namespace std; int main() { int a, b, c; cout<<"Enter two Numbers:"; cin >> a >> b; c = a / b; cout << c; return 0; }
Now, run the above code and enter the two numbers 20 and 5, and then you will get the following output.
Excellent. We are getting the perfect output. Now, again run the same code and enter the two numbers 20 and 0 and press the enter butter then you will get the following.
Once you press the enter button, you will get the following runtime error i.e. Division by Zero Exception.
This run time error we are getting because of the bad input. As soon as we enter two numbers with the second number as 0, and when the c = a/b statement is executed, the program stopped abnormally by throwing the above Exception. Now, the user may not be a programmer and by seeing the above exception, he may not be resolve the issue. Then as a programmer or developer, we need to handle such types of runtime errors and need to provide user-friendly error messages so that the user can understand the error message and take necessary actions to resolve the issue.
How to Implement Exception Handling in C++?
Let us first rewrite the previous example using Exception Handling in C++ and then we will try to understand the code.
#include <iostream> using namespace std; int main() { int a, b, c; cout << "Enter two Numbers:"; cin >> a >> b; try { if (b == 0) throw 1; c = a / b; cout << c; } catch (int e) { cout << "Division by zero"; } return 0; }
Here we have the main function. Inside this, we have declared 3 variables. Then we ask the user to enter two numbers that are going to be stored on the variables a and b. Then we created a try and catch block. Inside try, we have given a condition that is if b == 0 then throw 1. Then we assign c to a/b and print the value of c. Then we passed an integer to the catch block that is e and wrote a print statement that is “Division by zero”. Now run the above application. If you enter 20 and 5 (non-zero), then you will get the output as excepted and when you enter the second number as 0, you will get the message as Division by zero as shown in the below image.
Below is the construct that we have used in the above program.
Now let us understand this. Inside the try block, if there is any error then it will jump to the catch block and execute the statements inside the catch block. Suppose there are 2 lines in the try block and the error is in the first line then it will jump to the catch block. Suppose the error is in the second line so the first line will be executed and then the second line is an error so it will jump to catch block. If there is a 3rd line also then that will not be executed.
So, it depends on which line there is an error, up to there the statement will be executed. If there is an error, it will jump to the catch block. And if there are no errors inside the try block then the catch block will not execute. So, it is more like if and else statements. If there is no error then execute the try block and if there is an error then from that line the catch block will execute. The objective of try-catch and throw is given below.
- try: It represents a block of code that can throw an exception.
- catch: It represents a block of code that is executed when a particular exception is thrown.
- throw: It is used to throw an exception inside a try block.
So, in the above code, where is the error?
We are throwing an exception in the try block that is “throw 1”. So, we have to throw exceptions in C++. C++ compiler doesn’t have any built-in mechanism for throwing an exception so we have to check the error and throw the exception. Most peoples are familiar with Java and C#. And in Java and C# exceptions are thrown by the compiler. The compiler will check for it and write the code for throwing an exception but the C++ compiler doesn’t do that. We have to check for the error and throw an exception.
In the above code, we have written that if b == 0 then throw something. We have to throw something like we have thrown 1 but we can also throw 2, 34, etc. any number. Then this number will be caught by the catch block. So, we have thrown an integer value and catch is also taking an integer value. Then inside the catch block, a message will be displayed. That throw and catch just for linking it. So, there is no meaning to that number that we have thrown from the try block. That integer is just for linking them. Instead of 1, if we have thrown some error code like 413, 401, 102, etc. then we can write,
catch(int e){
cout << “Division by zero” << “error code” << e;
}
So, whatever the value comes in e that will be displayed on the screen. This is the reason for throwing an integer value in the try block. So, we can mention some codes in our program to easily identify the error. We can give documentation or manuals for the software to the user so that the user can identify the error from the error code.
Now let us understand the mechanism. When we enter the second number as 0, then 0 is assigned to the b variable. So, if the denominator is zero then the result of division will be undefined. So don’t want to divide by zero in our program. So, we have used a try and catch block to identify if the denominator is zero then inform the user and if the denominator is non-zero then perform the division. If b is not zero then the catch block will not be executed. If the condition is not failed, then the try block will not throw any integer value and it will execute the rest of the statements in the try block.
Example to Understand Try and Catch block in C++:
#include <iostream> using namespace std; int Division (int a, int b) throw (int) { if (b == 0) throw 1; return a / b; } int main() { int x, y, z; cout << "Enter two Numbers:"; cin >> x >> y; try { z = Division (x, y); cout << z << endl; } catch (int e) { cout << "Division by zero " << e << endl; } cout << "Bye" << endl; }
Output:
In the next article, I am going to discuss How to Throw and Catch Exception Between Functions in C++ with Examples. Here, in this article, I try to explain Exception Handling in C++ with Examples and I hope you enjoy this Exception Handling in C++ with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.