
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Type Conversion in C++
- Difference Between Type casting and Type Conversion
- 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#?
- Type Conversion in Python
- 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?
- Can we have a try block without a catch block in Java?
- What is Type Conversion?
- Data Type Conversion in Python
- What is the difference between implicit and explicit type conversion in C#?
- Can finally block be used without catch in Java?
- Can we have an empty catch block in Java?