Java/J2EE and SOA (349 Blogs) Become a Certified Professional

How To Implement Exception Handling In C++?

Last updated on Oct 31,2019 5.1K Views

How To Implement Exception Handling In C++?

Exceptions are abnormal conditions during run time or compile time. Exception Handling is a very essential concept in c++.  This article will introduce you to exception handling in C++ along with its different types.

Following pointers will be covered in this article,

So let us get started then,

Exception Handling In C++

Types Of Exceptions

There are two types of exception,

Run time Exception

It is an Exception caught during run time.

Compile-time Exception

It is an Exception caught during compile time.

Moving on with this Exception Handling article in C++,

What Is Exception Handling?

Errors disrupt normal execution of a program. Exception handling is very necessary, and it is the process of handling errors or exceptions. It makes sure that the execution of the program is not affected by the exceptions and slowly handles them without causing any issue to the program execution.

When you consider exception handling, there are three terms associated with it,

Try

The code inside this block is like a trial code, which might throw an exception. This exception is caught inside the catch block. 

Catch

The code in this block is executed when the code in the try blocks throws an exception.

Throw

This keyword is used to throw an exception when it is encountered. The exception is sent to the exception handler.

Syntax:

The code inside the try block is executed. If there is an error generated, then the keyword throw throws the exception to the exception handler, that is, the catch block. The catch block then executed the code, which is inside its block, thus handling the exception. 

Let us take a look at sample code for exception handling in c++

Sample Code

#include <iostream>
using namespace std;
try{
//code for try
throw &ldquo;exception&rdquo;;
}
catch(exception){
//code for catch
}
int main()
{
int x = 1;
try{
cout << "Try Block: "<<endl;
if(x < 10)
{
throw x;
}
}
catch (int x ) {
cout << "Catch Block: "<<endl;
}
cout<<"end of code:(after catch block) "<<endl;
return 0;
}

Output:

Output - Exception Handling In C++ - Edureka

Explanation

This program demonstrates exception handling. We have a variable x, which is assigned a value of 1. Then we have the start of the try block. In this block, we have an if statement with the condition x<10.

 In our case, the condition is true as x is one. The program then throws an exception and the control shifts to catch block. We execute the condition in catch part and exit the block.

catch (...) {
cout << "Default Exceptionn"<<endl;
}

Last, we execute the remaining statements after the catch block and exit program. 

There can be multiple catch statement, depending on the number of possible exceptions.

Moving on with this Exception Handling article in C++,

Catch Block Failure

Consider the previous program, if instead of x the throw keyword throws “ABC” then, the catch function will not be able to handle it. It will show an error,

We can have our won error message is displayed in such case.

To solve this, we need to add a default catch function to the code to handle such issues. 

#include <iostream>
using namespace std;
int main()
{
int x = 1;
try {
cout << "Try Block: "<<endl;
if(x < 10)
{
throw "ABC";
}
}
catch (int x ) {
cout << "Catch Block: n"<<endl;
}
catch(...){
cout << "Default Exceptionn"<<endl;
}
return 0;
}

Outtput:

Output - Exception Handling In C++ - Edureka

Explanation:

This code is similar to the previous one. The only change is that the exception thrown is of type char. This results in our catch function being useless. So we have included a default catch function. 

If none of the catch statements are matching, then the default catch is executed. 

Multiple Catch Blocks

There can be multiple catch blocks of a single try block.

Here is an example,

#include <iostream>
using namespace std;
int test(int a) {
try{
if(a < 0)
throw a;
else
throw 'a';
}catch(int a){
cout<<"Caught an integer: " << a<<endl;
}catch (char a){
cout<<"Caught a character: " << a<<endl;
}
return 0;
}
int main() {
cout<<"multiple catches:"<<endl;
test(10);
test(-1);
return 0;
}

Output:

Output - Exception Handling In C++ - Edureka

Explanation:

In the above code, we use multiple catch statements. We have a function test which generates an exception. In the first test case, the value is 10. Since 10 is greater than zero, ‘a’ the character is thrown and it is caught by the second catch function.

In the second case, the value is less than 0 so the value -1 is thrown and it is caught by integer exception

Exception Handling in the base and derived class:

If the base and derived class exceptions are caught then catch of derived class must be executed before the base class.

Here are some exceptions:

  • std::exception 

  • logic_error 

  • runtime_error 

  • bad_alloc 

  • bad_cast 

  • bad_exception 

With this we come to the end of this blog on ‘Exception Handling In C++’. I hope you found this informative and helpful, stay tuned for more tutorials on similar topics.You may also checkout our training program to get in-depth knowledge on jQuery along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of  this blog and we will get back to you.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 19th October,2024

19th October

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 14th December,2024

14th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.