C++ Exception Handling: Try, Catch, throw Example

What is Exception Handling in C++?

Exception handling in C++ provides you with a way of handling unexpected circumstances like runtime errors. So whenever an unexpected circumstance occurs, the program control is transferred to special functions known as handlers.

To catch the exceptions, you place some section of code under exception inspection. The section of code is placed within the try-catch block.

If an exceptional situation occurs within that section of code, an exception will be thrown. Next, the exception handler will take over control of the program.

In case no exceptional circumstance occurs, the code will execute normally. The handlers will be ignored.

In this C++ tutorial, you will learn:

Why Exception Handling?

Here, are the reason for using Exception Handling in C++:

  • You will separate your error handling code from your normal code. The code will be more readable and easier to maintain.
  • Functions can handle the exceptions they choose. Even if a function throws many exceptions, it will only handle some. The caller will handle the uncaught exceptions.

Exception Handling Keywords

Exception handling in C++ revolves around these three keywords:

  • throw– when a program encounters a problem, it throws an exception. The throw keyword helps the program perform the throw.
  • catch– a program uses an exception handler to catch an exception. It is added to the section of a program where you need to handle the problem. It’s done using the catch keyword.
  • try– the try block identifies the code block for which certain exceptions will be activated. It should be followed by one/more catch blocks.

Suppose a code block will raise an exception. The exception will be caught by a method using try and catch keywords. The try/catch block should surround code that may throw an exception. Such code is known as protected code.

Syntax:

The try/catch takes this syntax:

try {
   // the protected code
} catch( Exception_Name exception1 ) {
   // catch block
} catch( Exception_Name exception2 ) {
   // catch block
} catch( Exception_Name exceptionN ) {
   // catch block
}
  • Although we have one try statement, we can have many catch statements.
  • The ExceptionName is the name of the exception to be caught.
  • The exception1, exception2, and exceptionN are your defined names for referring to the exceptions.

Example 1:

#include<iostream>
#include<vector>
using namespace std;

int main() {
	vector<int> vec;
	vec.push_back(0);	
	vec.push_back(1);	
	// access the third element, which doesn't exist
	try
	{
		vec.at(2);		
	}
	catch (exception& ex)
	{
		cout << "Exception occurred!" << endl;
	}
	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in the program to use its functions.
  2. Include the vector header file in the program to use its functions.
  3. Include the std namespace in the program to its classes without calling it.
  4. Call the main() function. The program logic should be added within its body.
  5. Create a vector named vec to store integer data.
  6. Add the element 0 to the vector named vec.
  7. Add the element 1 to the vector named vec.
  8. A comment. It will be skipped by the C++ compiler.
  9. Use the try statement to catch an exception. The { marks the beginning of the body of try/catch block. The code added within the body will become the protected code.
  10. Try to access the element stored at index 2 (third element) of the vector named vec. This element doesn’t exist.
  11. End of the body of try/catch block.
  12. Catch the exception. The returned error message will be stored in the variable ex.
  13. Print out some message on the console if the exception is caught.
  14. End of the body of the catch block.
  15. The program should return a value upon successful execution.
  16. End of the main() function body.

Example 2:

#include <iostream>
using namespace std;
double zeroDivision(int x, int y) {

	if (y == 0) {
		throw "Division by Zero!";
	}
	return (x / y);
}

int main() {
	int a = 11;
	int b = 0;
	double c = 0;

	try {
		c = zeroDivision(a, b);
		cout << c << endl;
	}
	catch (const char* message) {
		cerr << message << endl;
	}
	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in the program to use its functions.
  2. Include the std namespace in the program to its classes without calling it.
  3. Create a function named zeroDivision that takes two integer arguments, x, and y. The function should return a double result.
  4. Use an if statement to check whether the value of variable argument y is 0. The { marks the beginning of if body.
  5. The message to be returned/thrown if y is 0.
  6. End of the body of the if statement.
  7. The zeroDivision function should return the value of x/y.
  8. End of the body of the zeroDivision function.
  9. Call the main() method. The { marks the beginning of this method.
  10. Declare an integer variable and assigning it the value 11.
  11. Declare an integer variable b and assigning it the value 0.
  12. Declare a double variable c and assigning it the value 0.
  13. Use the try statement to catch an exception. The { marks the beginning of the body of try/catch block. The code added within the body will become the protected code.
  14. Call the zeroDivision function and passing to arguments a and b, that is, 11 and 0. The result of this operation will be stored in variable c.
  15. Print out the value of variable c on the console.
  16. End of the body of try/catch block.
  17. Catch the exception. The returned error message will be stored in the variable message.
  18. Print out the returned error message on the console.
  19. End of the body of the catch block.
  20. The program should return a value upon successful execution.
  21. End of the main() function body.

C++ Standard Exceptions

C++ comes with a list of standard exceptions defined in <exception> class. These are described below:

Exception Description
std::exception This is an exception and the parent class of all standard C++ exceptions.
std::bad_alloc This exception is thrown by a new keyword.
std::bad_cast This is an exception thrown by dynamic_cast.
std::bad_exception A useful device for handling unexpected exceptions in C++ programs.
std::bad_typeid An exception thrown by typeid.
std::logic_error This exception is theoretically detectable by reading code.
std::domain_error This is an exception thrown after using a mathematically invalid domain.
std::invalid_argument An exception thrown for using invalid arguments.
std::length_error An exception thrown after creating a big std::string.
std::out_of_range Thrown by at method.
std::runtime_error This is an exception that cannot be detected via reading the code.
std::overflow_error This exception is thrown after the occurrence of a mathematical overflow.
std::range_error This exception is thrown when you attempt to store an out-of-range value.
std::underflow_error An exception thrown after the occurrence of mathematical underflow.

User-Defined Exceptions

The C++ std::exception class allows us to define objects that can be thrown as exceptions. This class has been defined in the <exception> header. The class provides us with a virtual member function named what.

This function returns a null-terminated character sequence of type char *. We can overwrite it in derived classes to have an exception description.

Example:

#include <iostream>
#include <exception>
using namespace std;

class newException : public exception
{
	virtual const char* what() const throw()
	{
		return "newException occurred";
	}
} newex;

int main() {

	try {
		throw newex;
		}
	catch (exception& ex) {
		cout << ex.what() << '\n';
	}
	return 0;	
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our program. We will use its functions without getting errors.
  2. Include the exception header file in our program. We will use its functions like what without errors.
  3. Include the std namespace in our program to use its classes without calling it.
  4. Create a new class named newException. This class inherits the exception class of C++.
  5. The beginning of the class body.
  6. Overwrite the virtual member function what() defined in the exception header file. We will then describe our own exception, the new exception.
  7. Start the definition of the new exception.
  8. The message to be returned if the new exception is caught.
  9. End of the definition of the new exception.
  10. End of the body of class newException. The newex is the name to be used to catch our new exception, after which the newException will be called.
  11. Call the main() function. The program logic should be added within its body. The { marks the beginning of its body.
  12. Use a try statement to mark the code within which we need to mark the exception. The { marks the beginning of the body of try/catch block. The code surrounded by this will become protected.
  13. Throw the newex exception if it’s caught.
  14. End of the try body.
  15. Use the catch statement to catch the exception. The exception error message will be stored in variable ex.
  16. Print the exception error message on the console.
  17. End of the body of catch statement.
  18. The program should return a value if it executes successfully.
  19. End of the body of the main() function.

Summary:

  • With exception handling in C++, you can handle runtime errors.
  • Runtime errors are the errors that occur during program execution.
  • Exception handling helps you handle any unexpected circumstances in your program.
  • When the unexpected circumstance occurs, program control is transferred to handlers.
  • To catch an exception, you place a section of code under the try-catch block.
  • The throw keyword helps the program throw exceptions, helping the program to handle the problem.
  • The try keyword helps identify the code block for which certain exceptions will be activated.
  • We can overwrite the what() function of the exception header file to define our exceptions.