
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Catch block and type conversion in C++
In this section, we will see how to use the catch block for exception handling and the type conversion in C++.
At first, let us see a code, and we will see what will be the output, and how they are generating.
Example
#include <iostream> using namespace std; int main() { try{ throw 'a'; } catch(int a) { cout << "Integer value is caught :" << a; } catch(...) { cout << "Entering into default catch block"; } }
Output
Entering into default catch block
So, what is the reason behind this. Why this kind of output is generating? As we can see the character ‘a’ is thrown, but the first catch block is for int. If we think that the ASCII of ‘a’ is an integer, so will be entering into the first block, but that kind of conversions are not applicable for the catch blocks.
Let us see another example. In this example we will see the conversion constructor is not called for the thrown objects.
Example
#include <iostream> using namespace std; class TestExcept1 {}; class TestExcept2 { public: TestExcept2 (const TestExcept1 &e ){ // Defining the Conversion constructor cout << "From the Conversion constructor"; } }; main() { try{ TestExcept1 exp1; throw exp1; } catch(TestExcept2 e2) { cout << "Caught TestExcept2 " << endl; } catch(...) { cout << "Entering into default catch block " << endl; } }
Output
Entering into default catch block
The derived type objects are not converted to the base type objects while the derived type objects are thrown.
- Related Articles
- Type Conversion in C++
- Can we declare a try catch block within another try catch block in Java?
- What is Type conversion in C#?
- What is the difference between type conversion and type casting in C#?
- What is the catch block in Java?
- Explain Try/Catch/Finally block in PowerShell
- Is it possible to catch multiple Java exceptions in single catch block?
- Difference Between Type casting and Type Conversion
- Type Conversion in Python
- Can we have a try block without a catch block in Java?\n
- Can finally block be used without catch in Java?
- Can we have an empty catch block in Java?
- Can we to override a catch block in java?
- What is the difference between implicit and explicit type conversion in C#?
- Data Type Conversion in Python
