Exception Handling in C++: Try, Catch and Throw Keywords

Exception Handling in C++: Try, Catch and Throw Keywords

12 Apr 2024
Advanced
2.84K Views
18 min read
Learn via Video Course & by Doing Hands-on Labs

C++ Programming For Beginners

Exception Handling in C++: An Overview

Exception Handling in C++ deals with the techniques to deal with unwanted and unexpected events occurring during the program execution. With learning C++, one must be ready to deal with errors, unexpected inputs, or other exceptions. However, exception handling in C++ makes it simpler, allowing your programs to run efficiently. In this blog post of C++ tutorial, we'll discuss how to use C++'s tools for exception handling. To increase your knowledge of C++ you can also take our C++ online training.

What is an Exception in C++?

Exceptions are runtime errors. Many a time, your program looks error-free during compilation. But, at the time of execution, some unexpected errors or events or objects come to the surface and the program prints an error message and stops executing. Such unexpected happenings are calledexceptions in C++.

Example

int a = 8/0;

In the above example, the program will show an error during runtime because divide by zero is undefined.

Exception Handling in C++

Exception handling in C++ is a technique to deal with exceptions. It maintains your program flow despite runtime errors in the code and, thus prevents unanticipated crashes. By providing error details, cutting down on development time, and improving user happiness, it facilitates troubleshooting. It's essential for developing a trustworthy and safe programming environment.

Exception Classes in C++

There are many standardexceptions in C++. All the standard exceptions are defined in the exception header file in C++. Thus all the standard exception classes are derived from the std::exception class in C++.

ExceptionDescription

std::exception

It is an exception as well as a parent class of all standard exceptions of C++.

std::logic_failure

This particular exception can be detected by reading any code.

std::runtime_error

This exception cannot be detected by reading any code.

std::bad_exception

This exception is used to handle unexpected exceptions in a C++ program.

std::bad_cast

This exception is generally thrown by dynamic_cast.

std::bad_typeid

This particular exception is generally thrown by typeid.

std::bad_alloc

This exception is generally thrown by new.

Read More - C++ Interview Interview Questions and Answers

Keywords for Exception Handling in C++

Keywords for Exception Handling in C++

  • try: the block of code defined under this statement is being tested for runtime errors.
  • throw: throws an exception when an error is detected. It is not necessary to use this keyword while using standard C++ exceptions.
  • catch: specifies the code block to be executed if an exception occurs in the try block.

Syntax

try {
 // code to check exceptions
 throw exception;
}

catch (exception) {
 // code to handle exceptions
} 

Every try block is followed by the catch block. The throw statement throws an exception, which is caught by the catch block. The catch block cannot be used without the try block

Example in C++ Compiler

// program to divide two numbers and throw an exception if the divisor is 0

#include <iostream>
using namespace std;

int main() {
 float numerator, denominator, result;
 cout << "Enter the numerator: ";
 cin >> numerator;
 cout << "Enter the denominator: ";
 cin >> denominator;

 try {
 // throw an exception if denominator is 0
 if (denominator == 0)
 throw 0;
 result = numerator / denominator; //if denominator not zero
 cout << numerator << " / " << denominator << " = " << result << endl;
 } 

 catch (float exception) {
 cout << "Error: Cannot divide by " << exception << endl;
 }
 return 0;
}
  • In the above code, we have put the result = numerator / denominator in the try block because this statement must not be executed if the denominator is 0. If the denominator is 0, the statements after the throw statement in the try block is skipped.
  • The catch block catches the thrown exception as its parameter and executes the statements inside it.
  • Here, the exception is of type int. Therefore, the catch statement accepts a int parameter.
  • If there isn't any exception thrown, the catch block gets skipped.

Output

When the denominator=0.
Enter numerator: 8
Enter denominator: 0
Error: Cannot divide by 0

Output

When the denominator is not 0.
Enter the numerator: 8
Enter the denominator: 2
8 / 2 = 4

  • You can also use the throw keyword to output a reference number, like a custom error number/code for organizing purposes:

    Example

    #include <iostream>
    using namespace std;
    
    int main() {
     int numerator, denominator, result;
     cout << "Enter the numerator: " << '\n';
     cin >> numerator;
     cout << "Enter the denominator: " << '\n';
     cin >> denominator;
     try {
     // throw an exception if denominator is 0
     if (denominator == 0)
     throw 505;
     result = numerator / denominator; //if denominator not zero
     cout << numerator << " / " << denominator << " = " << result << endl;
     }
     catch (int myNum) {
     cout << "Error: Cannot divide by " << myNum << endl;
     }
     return 0;
    }
    

    Output

    When the denominator=0.
    Enter numerator: 8
    Enter denominator: 0
    Error: Cannot divide by 0
    

    Output

    When the denominator is not 0.
    Enter the numerator: 8
    Enter the denominator: 2
    8 / 2 = 4
    

Handling All Types of Exceptions (...)

Suppose we do not know the types of exceptions that can occur in our try block or the throw type used in the try block, then we can use the ellipsis symbol ... as our catch parameter. catch (...) is known as the catch-all exception handler.

Syntax

try {
 // code to check exceptions
}
catch (...) {
 // code to handle exceptions
} 

Example

#include <iostream>
using namespace std;

int main() {
 float numerator, denominator, result;
 cout << "Enter the numerator: " << '\n';
 cin >> numerator;
 cout << "Enter the denominator: " << '\n';
 cin >> denominator;

 try {
 // throw an exception if denominator is 0
 if (denominator == 0)
 throw 0;
 result = numerator / denominator; //if denominator not zero
 cout << numerator << " / " << denominator << " = " << result << endl;
 } 

 catch (...) {
 cout << "Error: Cannot divide by " << endl;
 }
 return 0;
}

Output

When the denominator=0

Enter numerator: 8
Enter denominator: 0
Error: Cannot divide by 0

Output

When the denominator is not 0.

Enter the numerator: 8
Enter the denominator: 2
8 / 2 = 4

Multiple Catch statements in C++ Exception Handling

This is like an if else-if ladder. Here, we can use multiple catch statements for different kinds of exceptions that can occur from a single block of code in the try block.

Syntax

 try {
 // code to check exceptions
 } 
 catch (exception1) {
 // code to handle exception

 } 
 catch (exception2) {
 // code to handle exception
 }
 .
 .
 . 
 catch (...) {
 // code code to handle exception
 }
  • Here, our program matches the type of exception that occurred in the try block with the catch statements.
  • If the exception that occurred matches any of the normal catch statements, that particular catch block gets executed.
  • If the exception occurred matches none of the normal catch statements, the catch-all exception handler, catch (...) gets executed.
  • The catch (...) statement acts as the default catch statement. Therefore, it must always be the final block in the try...catch statement
  • It is not necessary to have a default catch block in the program.

Example in C++ Online Editor

 #include <iostream>
 using namespace std;
 
 int main() {
 
 float numerator, denominator, arr[] = {1, 2, 3, 4, 5};
 int index;
 cout << "Enter array index: ";
 cin >> index;
 
 try {
 
 // throw exception if array is out of bounds
 if (index >= sizeof(arr))
 throw "Error: Array out of bounds!";
 
 // not executed if array is out of bounds
 cout << "Enter numerator: ";
 cin >> numerator;
 
 cout << "Enter denominator: ";
 cin >> denominator;
 
 // throw exception if denominator is 0
 if (denominator == 0)
 throw 0;
 
 // not executed if denominator is 0
 arr[index] = numerator / denominator;
 cout << arr[index] << endl;
 }
 
 // catch "Array out of bounds" exception
 catch (const char* msg) {
 cout << msg << endl;
 }
 // catch "Divide by 0" exception
 catch (float num) {
 cout << "Error: Cannot divide by " << num << endl;
 }
 
 // catch any other exception
 catch (...) {
 cout << "Unexpected exception!" << endl;
 }
 
 return 0; 
 }

In the above code, we are dividing two numbers and storing their result in an array arr at the index value given by the user. There can be two possible exceptions here:

  • Array index out of bounds: the indexvalue given by the user is greater than the size of the array
  • Divide by 0: If the denominator is 0.

If there occurs any other exception in the try block, it will be caught by the catch(...) statement.

Output

  • If the user enters a valid input.
     Enter array index: 3
     Enter numerator: 10
     Enter denominator: 2
     5
  • If the user inputs an invalid index
     Enter array index: 5
     Error: Array out of bounds!
  • If the denominator is 0
     Enter array index: 2
    Enter numerator: 8
    Enter denominator: 0
    Error: Cannot divide by 0
  • If any unexpected exception occurs
     Enter array index: 2
     Enter numerator: "sScholarHat" // Entering a string instead of a number
     Unexpected exception!
Summary

Unexpected errors that arise while a program is running can be handled with C++ exception handling. You can learn more about exception handling in C++ with examples in C++ certification courses, providing a flexible mechanism for managing both anticipated and unanticipated errors.

FAQs

Q1. What is Exception Handling in C++?

Unexpected problems that occur while a program is running can be managed and recovered by using C++'s exception-handling framework.

Q2. What is the main use of exception handling?

Exception handling is primarily used to gently manage errors, ensuring that programs can bounce back from unusual circumstances without crashing.

Q3. What are the keywords used in exception handling?

try, catch, and, throw are all keywords that are used in exception handling.

Q4. What are the disadvantages of exception handling?

If exceptions are used excessively, disadvantages of exception handling may include increased code complexity as well as overhead.

Q5. What is the difference between checked and unchecked exceptions?

Unchecked exceptions (runtime exceptions) do not need to be explicitly handled; instead, they must be captured or expressly specified in the method signature for checked exceptions.

Q6. What are the three exception keywords?

Try, catch, and throw the three exception keywords in C++ for catching all exceptions.

Q7. What is try, catch and throw in C++?

In C++, the words throw and try are used to raise custom exceptions, catch is used to catch exceptions, and try is used to enclose code that could throw exceptions.
Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A
  • 10+ Real-world Projects
  • Career Coaching
  • Email Support
Upto 66% OFF
KNOW MORE..

To get full access to all courses

Accept cookies & close this