Javatpoint Logo
Javatpoint Logo

Multiple Catch Statements in C++

An essential component of creating reliable software is exception handling. It enables us to react politely to unforeseen circumstances that might happen while the program is running. Developers can precisely handle a variety of exception types due to C++'s robust exception handling framework. In this article, we will discuss the concept of numerous catch statements in C++, along with examples of how they can be used to manage various uncommon situations.

The C++ try, catch, and throw keywords are used to handle exceptions. A similar catch block is run when an extraordinary circumstance arises inside a try block to handle the exception. An exception is raised by using the throw keyword, and catch blocks are used to indicate how certain exceptions should be handled.

The Need of Several Catch Blocks:

A program may frequently run across various exception kinds, each of which calls for a distinct reaction. Here, having many catch blocks is really useful. We can have numerous catch blocks, each one created to deal with a particular exception type, rather than utilizing a single catch block to handle all exceptions.

Syntax:

It has the following syntax:

Example 1:

Handling invalid input with divide-by-zero

Let's look at a simple situation in which we divide two numbers, but we also need to handle two different exceptions: divide-by-zero and invalid input.

Output

Enter dividend: 10
Enter divisor: 0
Error: Division by zero is not allowed.

Enter dividend: 10
Enter divisor: a
Unknown exception occurred.

Explanation:

In this example, we employ two catch blocks: one to handle exceptions of type const char* (for divide-by-zero) and another to handle all other exceptions (for incorrect input).

Example 2:

Custom Exception Classes Handling:

Using inheritance from the std::exception class, custom exception classes can be created in C++. Let's develop a special exception type and show how to handle it in addition to common exceptions.

Output

Custom Exception: Something went wrong.

Explanation:

In this example, we have two catch blocks, one for the unique exception MyException and one for the common exception std::exception.

Conclusion:

In C++, several catch statements offer a potent method for precisely handling various exception kinds. We can make sure that the program responds effectively to a variety of unusual events by organizing catch blocks to match particular exception kinds, improving the program's reliability and maintainability. Every C++ programmer should be able to comprehend and use numerous catch blocks, as doing so will help them create stronger, more error-tolerant programs.


Next TopicThread pool in C++





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA