C++ Exception Handling
While running a program, sometimes an unexpected problem occurs. For example, a program may try to divide a number by zero or receive a value that it cannot process correctly.
Instead of allowing the program to stop suddenly, C++ provides C++ Exception Handling. It allows you to detect an error, handle it, and continue the program in a controlled way.
The main keywords used for exception handling are try, catch, and throw.
try Block in C++
The try block contains the code that may cause an exception.
try
{
// code that may cause an exception
}
The try block is normally followed by one or more catch blocks that handle the exception.
try catch in C++
The catch block handles an exception thrown from the try block.
Example
try
{
int age = -5;
if (age < 0)
throw age;
}
catch (int value)
{
cout << "Invalid age: " << value;
}
Output
Invalid age: -5
Here, throw sends the invalid value to the catch block. The catch block then handles the problem.
This is the basic idea behind try catch in C++.
throw in C++
The throw keyword is used to signal that an exception has occurred.
int age = -2;
if (age < 0)
{
throw age;
}
The value after throw is passed to a matching catch block.
You can throw different types of values, such as integers, strings, or objects.
throw 10;
throw "Invalid value";
A throw statement transfers control from the current code to a suitable catch block.
Handling Division by Zero
A common example of exception handling is checking for division by zero.
int a = 10;
int b = 0;
try
{
if (b == 0)
throw "Cannot divide by zero";
cout << a / b;
}
catch (const char* message)
{
cout << message;
}
Output
Cannot divide by zero
Instead of performing an invalid calculation, the program throws an exception and handles it.
Multiple Catch in C++
A try block can have more than one catch block. This allows you to handle different types of exceptions differently.
try
{
throw 10;
}
catch (int value)
{
cout << "Integer exception";
}
catch (double value)
{
cout << "Double exception";
}
catch (const char* message)
{
cout << "String exception";
}
Since an integer was thrown, the first catch block handles it.
This is called Multiple Catch in C++.
You can also use a general catch block:
catch (...)
{
cout << "Some exception occurred";
}
The ... catches an exception of any type that was not already handled by an earlier matching catch.
Nested try
A try block can be placed inside another try block. This is called a nested try block.
try
{
try
{
throw 10;
}
catch (int value)
{
cout << "Inner catch" << endl;
throw;
}
}
catch (int value)
{
cout << "Outer catch";
}
Output
Inner catch
Outer catch
Here, the inner catch handles the exception first and then uses throw; to pass the same exception to the outer catch.
Custom Exceptions in C++
Sometimes the standard exception types are not enough for your program. You can create your own exception class.
class InvalidAge
{
public:
string message = "Age cannot be negative";
};
You can throw an object of this class:
try
{
int age = -5;
if (age < 0)
throw InvalidAge();
}
catch (InvalidAge e)
{
cout << e.message;
}
Output
Age cannot be negative
For larger programs, custom exceptions can make errors easier to identify and handle.
Frequently Asked Questions (FAQs)
Q1. What are tokens in C++?
C++ Tokens are the smallest individual elements of a C++ program. They include keywords, identifiers, literals, operators, and special symbols that the compiler recognizes while processing the source code.
Q2. What is the difference between C++ keywords and identifiers?
C++ Keywords are reserved words with predefined meanings, such as int, if, and return, whereas C++ Identifiers are user-defined names used for variables, functions, classes, and other program elements. Identifiers cannot use reserved keywords as names.
Q3. What is a namespace in C++, and why is it used?
A C++ Namespace is used to organize code and prevent naming conflicts between variables, functions, and classes. The std namespace, for example, contains many standard library components like cout and cin.
Q4. What is the scope resolution operator (::) in C++?
The scope resolution operator (::) is used to access members of a namespace or class and to define class member functions outside the class definition. It also helps distinguish between local and global variables when they share the same name.
Q5. What is the purpose of preprocessor directives in C++?
Preprocessor directives are instructions that are processed before compilation begins. They are commonly used to include header files (#include), define macros (#define), and control conditional compilation.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
