Catch block and type conversion in C++

Predict the output of following C++ program.

#include <iostream>
using namespace std;
int main()
{
    try
    {
        throw 'x';
    }
    catch(int x)
    {
        cout << " Caught int " << x;
    }
    catch(...)
    {
        cout << "Defaule catch block";
    }
}
Defaule catch block

In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object.

#include <iostream>
using namespace std;
class MyExcept1 {};
class MyExcept2
{
public:
    // Conversion constructor
    MyExcept2 (const MyExcept1 &e )
    {
        cout << "Conversion constructor called";
    }
};
int main()
{
    try
    {
        MyExcept1 myexp1;
        throw myexp1;
    }
    catch(MyExcept2 e2)
    {
        cout << "Caught MyExcept2 " << endl;
    }
    catch(...)
    {
        cout << " Defaule catch block " << endl;
    }
    return 0;
}
Defaule catch block

As a side note, the derived type objects are converted to base typr when a derived object is thrown and there is a catch block to catch base type.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/catch-block-and-type-conversion-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Catching base and derived classes as exceptions

Exception Handling – catching base and derived classes as exceptions:

If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class.

If we put base class first then the derived class catch block will never be reached. For example, following C++ code prints “Caught Base Exception”

#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
   Derived d;
   // some other stuff
   try {
       // Some monitored code
       throw d;
   }
   catch(Base b) {
        cout<<"Caught Base Exception";
   }
   catch(Derived d) {  //This catch block is NEVER executed
        cout<<"Caught Derived Exception";
   }
   getchar();
   return 0;
}

In the above C++ code, if we change the order of catch statements then both catch statements become reachable. Following is the modifed program and it prints “Caught Derived Exception”

#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
   Derived d;
   // some other stuff
   try {
       // Some monitored code
       throw d;
   }
   catch(Derived d) {
        cout<<"Caught Derived Exception";
   }
   catch(Base b) {
        cout<<"Caught Base Exception";
   }
   getchar();
   return 0;
}

In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code.
For example, following Java code fails in compilation with error message “exception Derived has already been caught”

//filename Main.java
classBase extendsException {}
classDerived extendsBase  {}
publicclassMain {
  publicstaticvoidmain(String args[]) {
    try{
       thrownewDerived();
    }
    catch(Base b) {}
    catch(Derived d) {}
  }
}

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/g-fact-60/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Stack Unwinding in C++

The process of removing function entries from function call stack at run time is called Stack Unwinding. Stack Unwinding is generally related to Exception Handling. In C++, when an exception occurs, the function call stack is linearly searched for the exception handler, and all the entries before the function with exception handler are removed from the function call stack. So exception handling involves Stack Unwinding if exception is not handled in same function (where it is thrown).

For example, output of the following program is:

 f3() Start
 f2() Start
 f1() Start
 Caught Exception: 100
 f3() End
#include <iostream>
 
using namespace std;
// A sample function f1() that throws an int exception
void f1() throw (int) {
  cout<<"\n f1() Start ";
  throw 100;
  cout<<"\n f1() End ";
}
// Another sample function f2() that calls f1()
void f2() throw (int) {
  cout<<"\n f2() Start ";
  f1();
  cout<<"\n f2() End ";
}
 
// Another sample function f3() that calls f2() and handles exception thrown by f1()
void f3() {
  cout<<"\n f3() Start ";
  try {
    f2();
  }
  catch(int i) {
   cout<<"\n Caught Exception: "<<i;
  }
  cout<<"\n f3() End";
}
// A driver function to demonstrate Stack Unwinding  process
int main() {
  f3();
 
  getchar();
  return 0;
}

In the above program, when f1() throws exception, its entry is removed from the function call stack (because it f1() doesn’t contain exception handler for the thrown exception), then next entry in call stack is looked for exception handler. The next entry is f2(). Since f2() also doesn’t have handler, its entry is also removed from function call stack. The next entry in function call stack is f3(). Since f3() contains exception handler, the catch block inside f3() is executed, and finally the code after catch block is executed. Note that the following lines inside f1() and f2() are not executed at all.

//inside f1()
  cout<<"\n f1() End ";
//inside f2()
  cout<<"\n f2() End ";

On a side note, if there were some local class objects inside f1() and f2(), destructors for those local objects would have been called in Stack Unwinding process.

Stack Unwinding also happens in Java when exception is not handled in same function.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/stack-unwinding-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Exception Handling in C++

One of the advantages of C++ over C is Exception Handling. C++ provides following specialized keywords for this purpose.

try: represents a block of code that can throw an exception.

catch: represents a block of code that is executed when a particular exception is thrown.

throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.

Why Exception Handling?

Following are main advantages of exception handling over traditional error handling.

1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow.

2) Functions/Methods can handle any exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it)

3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.

Exception Handling in C++

1) Following is a simple example to show exception handling in C++. The output of program explains flow of execution of try/catch blocks.

#include <iostream>

using namespace std;

int main()

{

int x = -1;

// Some code

cout << "Before try \n";

try {

cout << "Inside try \n";

if (x < 0)

{

throw x;

cout << "After throw (Never executed) \n";

}

}

catch (int x ) {

cout << "Exception Caught \n";

}

cout << "After catch (Will be executed) \n";

return 0;

}

Output:

Before try
Inside try
Exception Caught
After catch (Will be executed)

2) There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch(…) block will be executed.

#include <iostream>

using namespace std;

int main()

{

try {

throw 10;

}

catch (char *excp) {

cout << "Caught " << excp;

}

catch (...) {

cout << "Default Exception\n";

}

return 0;

}

Output:

Default Exception

3) Implicit type conversion doesn’t happen for primitive types. For example, in the following program ‘a’ is not implicitly converted to int

#include <iostream>

using namespace std;

int main()

{

try {

throw 'a';

}

catch (int x) {

cout << "Caught " << x;

}

catch (...) {

cout << "Default Exception\n";

}

return 0;

}

Output:

Default Exception

4) If an exception is thrown and not caught anywhere, the program terminates abnormally. For example, in the following program, a char is thrown, but there is no catch block to catch a char.

#include <iostream>

using namespace std;

int main()

{

try {

throw 'a';

}

catch (int x) {

cout << "Caught ";

}

return 0;

}

Output:

terminate called after throwing an instance of 'char'
This application has requested the Runtime to terminate it in an 
unusual way. Please contact the application's support team for 
more information.

We can change this abnormal termination behavior by writing our own unexpected function.

5) A derived class exception should be caught before a base class exception. See this for more details.

6) Like Java, C++ library has a standard exception class which is base class for all standard exceptions. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type

7) Unlike Java, in C++, all exceptions are unchecked. Compiler doesn’t check whether an exception is caught or not (See this for details). For example, in C++, it is not necessary to specify all uncaught exceptions in a function declaration. Although it’s a recommended practice to do so. For example, the following program compiles fine, but ideally signature of fun() should list unchecked exceptions.

#include <iostream>

using namespace std;

// This function signature is fine by the compiler, but not recommended.

// Ideally, the function should specify all uncaught exceptions and function

// signature should be "void fun(int *ptr, int x) throw (int *, int)"

void fun(int *ptr, int x)

{

if (ptr == NULL)

throw ptr;

if (x == 0)

throw x;

/* Some functionality */

}

int main()

{

try {

fun(NULL, 0);

}

catch(...) {

cout << "Caught exception from fun()";

}

return 0;

}

Output:

Caught exception from fun()

8) In C++, try-catch blocks can be nested. Also, an exception can be re-thrown using “throw; ”

#include <iostream>

using namespace std;

int main()

{

try {

try {

throw 20;

}

catch (int n) {

cout << "Handle Partially ";

throw; //Re-throwing an exception

}

}

catch (int n) {

cout << "Handle remaining ";

}

return 0;

}

Output:

Handle Partially Handle remaining

A function can also re-throw a function using same “throw; “. A function can handle a part and can ask the caller to handle remaining.

9) When an exception is thrown, all objects created inside the enclosing try block are destructed before the control is transferred to catch block.

#include <iostream>

using namespace std;

class Test {

public:

Test() { cout << "Constructor of Test " << endl; }

~Test() { cout << "Destructor of Test " << endl; }

};

int main() {

try {

Test t1;

throw 10;

} catch(int i) {

cout << "Caught " << i << endl;

}

}

Output:

Constructor of Test
Destructor of Test
Caught 10

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/exception-handling-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Catching base and derived classes as exceptions

Exception Handling – catching base and derived classes as exceptions:

If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class.

If we put base class first then the derived class catch block will never be reached. For example, following C++ code prints “Caught Base Exception”

#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
   Derived d;
   // some other stuff
   try {
       // Some monitored code
       throw d;
   }
   catch(Base b) {
        cout<<"Caught Base Exception";
   }
   catch(Derived d) {  //This catch block is NEVER executed
        cout<<"Caught Derived Exception";
   }
   getchar();
   return 0;
}

In the above C++ code, if we change the order of catch statements then both catch statements become reachable. Following is the modifed program and it prints “Caught Derived Exception”

#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
   Derived d;
   // some other stuff
   try {
       // Some monitored code
       throw d;
   }
   catch(Derived d) {
        cout<<"Caught Derived Exception";
   }
   catch(Base b) {
        cout<<"Caught Base Exception";
   }
   getchar();
   return 0;
}

In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code.
For example, following Java code fails in compilation with error message “exception Derived has already been caught”

//filename Main.java
classBase extendsException {}
classDerived extendsBase  {}
publicclassMain {
  publicstaticvoidmain(String args[]) {
    try{
       thrownewDerived();
    }
    catch(Base b) {}
    catch(Derived d) {}
  }
}

 

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/g-fact-60/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Stack Unwinding in C++

The process of removing function entries from function call stack at run time is called Stack Unwinding. Stack Unwinding is generally related to Exception Handling. In C++, when an exception occurs, the function call stack is linearly searched for the exception handler, and all the entries before the function with exception handler are removed from the function call stack. So exception handling involves Stack Unwinding if exception is not handled in same function (where it is thrown).

For example, output of the following program is:

 f3() Start
 f2() Start
 f1() Start
 Caught Exception: 100
 f3() End
#include <iostream>
 
using namespace std;
// A sample function f1() that throws an int exception
void f1() throw (int) {
  cout<<"\n f1() Start ";
  throw 100;
  cout<<"\n f1() End ";
}
// Another sample function f2() that calls f1()
void f2() throw (int) {
  cout<<"\n f2() Start ";
  f1();
  cout<<"\n f2() End ";
}
 
// Another sample function f3() that calls f2() and handles exception thrown by f1()
void f3() {
  cout<<"\n f3() Start ";
  try {
    f2();
  }
  catch(int i) {
   cout<<"\n Caught Exception: "<<i;
  }
  cout<<"\n f3() End";
}
// A driver function to demonstrate Stack Unwinding  process
int main() {
  f3();
 
  getchar();
  return 0;
}

In the above program, when f1() throws exception, its entry is removed from the function call stack (because it f1() doesn’t contain exception handler for the thrown exception), then next entry in call stack is looked for exception handler. The next entry is f2(). Since f2() also doesn’t have handler, its entry is also removed from function call stack. The next entry in function call stack is f3(). Since f3() contains exception handler, the catch block inside f3() is executed, and finally the code after catch block is executed. Note that the following lines inside f1() and f2() are not executed at all.

//inside f1()
  cout<<"\n f1() End ";
//inside f2()
  cout<<"\n f2() End ";

On a side note, if there were some local class objects inside f1() and f2(), destructors for those local objects would have been called in Stack Unwinding process.

Stack Unwinding also happens in Java when exception is not handled in same function.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/stack-unwinding-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Catch block and type conversion in C++

Predict the output of following C++ program.

#include <iostream>
using namespace std;
int main()
{
    try
    {
        throw 'x';
    }
    catch(int x)
    {
        cout << " Caught int " << x;
    }
    catch(...)
    {
        cout << "Defaule catch block";
    }
}
Defaule catch block

In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object.

#include <iostream>
using namespace std;
class MyExcept1 {};
class MyExcept2
{
public:
    // Conversion constructor
    MyExcept2 (const MyExcept1 &e )
    {
        cout << "Conversion constructor called";
    }
};
int main()
{
    try
    {
        MyExcept1 myexp1;
        throw myexp1;
    }
    catch(MyExcept2 e2)
    {
        cout << "Caught MyExcept2 " << endl;
    }
    catch(...)
    {
        cout << " Defaule catch block " << endl;
    }
    return 0;
}
Defaule catch block

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/catch-block-and-type-conversion-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Type Conversion in C

A type cast is basically a conversion from one type to another. There are two types of type conversion:

  1. Implicit Type Conversion Also known as ‘automatic type conversion’.
    • Done by the compiler on its own, without any external trigger from the user.
    • Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.
    • All the data types of the variables are upgraded to the data type of the variable with largest data type.
          
             bool -> char -> short int -> int -> 
             unsigned int -> long -> unsigned -> 
             long long -> float -> double -> long double
      
    • It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).

    Example of Type Implicit Conversion:

    // An example of implicit conversion
    #include<stdio.h>
    int main()
    {
        int x = 10;    // integer x
        char y = 'a'// character c
        // y implicitly converted to int. ASCII
        // value of 'a' is 97
        x = x + y;
       
        // x is implicitly converted to float
        float z = x + 1.0;
        printf("x = %d, z = %f", x, z);
        return 0;
    }

    Output:

    x = 107, z = 108.000000
  1. Explicit Type Conversion– This process is also called type casting and it is user defined. Here the user can type cast the result to make it of a particular data type.The syntax in C:
    (type) expression

    Type indicated the data type to which the final result is converted.

    // C program to demonstrate explicit type casting
    #include<stdio.h>
    int main()
    {
        double x = 1.2;
        // Explicit conversion from double to int
        int sum = (int)x + 1;
        printf("sum = %d", sum);
        return 0;
    }

    Output:

    sum = 2

    Advantages of Type Conversion

    • This is done to take advantage of certain features of type hierarchies or type representations.
    • It helps us to compute expressions containing variables of different data types.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/type-conversion-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Character arithmetic in C and C++

As already known character known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. To understand better let’s take an example.

// C program to demonstrate character arithmetic.

#include <stdio.h>

int main()

{

char ch1 = 125, ch2 = 10;

ch1 = ch1 + ch2;

printf("%d\n", ch1);

printf("%c\n", ch1 - ch2 - 4);

return 0;

}

Output:

-121
y

So %d specifier causes an integer value to be printed and %c specifier causes a character value to printed. But care has to taken that while using %c specifier the integer value should not exceed 127.
So far so good.

But for c++ it plays out a little different.

Look at this example to understand better.

// A C++ program to demonstrate character

// arithmetic in C++.

#include <bits/stdc++.h>

using namespace std;

int main()

{

char ch = 65;

cout << ch << endl;

cout << ch + 0 << endl;

cout << char(ch + 32) << endl;

return 0;

}

Output:

A
65
a

Without a ‘+’ operator character value is printed. But when used along with ‘+’ operator behaved differently. Use of ‘+’ operator implicitly typecasts it to an ‘int’. So to conclude, in character arithmetic, typecasting of char variable to ‘char’ is explicit and to ‘int’ it is implicit.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/character-arithmetic-c-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Difference between %d and %i format specifier in C language

A format specifier is a sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. In short it tell us which type of data to store and which type of data to print.

For example — If we want to read and print integer using scanf() and printf() function, either %i or %d is used but there is subtle difference in both %i and %d format specifier.

%d specifies signed decimal integer while %i specifies integer.

%d and %i behave similar with printf

There is no difference between the %i and %d format specifiers for printf. Consider a following example.

// C program to demonstrate

// the behavior of %i and %d

// with printf statement

#include <stdio.h>

int main()

{

int num = 9;

// print value using %d

printf("Value of num using %%d is = %d\n", num);

// print value using %i

printf("Value of num using %%i is = %i\n", num);

return 0;

}

Run on IDE

Output:
Value of num using %d is = 9
Value of num using %i is = 9

%d and %i behavior is different in scanf

%d assume base 10 while %i auto detects the base. Therefore, both specifiers behaves differently while they are used with an input specifier. So, 012 would be 10 with %i but 12 with %d.

  • %d takes integer value as signed decimal integer i.e. it takes negative values along with positive values but values should be in decimal otherwise it will print garbage value. Consider a following example.
  • %i takes integer value as integer value with decimal, hexadecimal or octal type.
    To enter a value in hexadecimal format — value should be provided by preceding “0x” and value in octal format — value should be provided by preceding “0”.

Consider a following example.

// C program to demonstrate the difference

// between %i and %d specifier

#include <stdio.h>

int main()

{

int a, b, c;

printf("Enter value of a in decimal format:");

scanf("%d", &a);

printf("Enter value of b in octal format: ");

scanf("%i", &b);

printf("Enter value of c in hexadecimal format: ");

scanf("%i", &c);

printf("a = %i, b = %i, c = %i", a, b, c);

return 0;

}

Run on IDE

Output:
Enter value of a in decimal format:12
Enter value of b in octal format: 012
Enter value of c in hexadecimal format: 0x12
a = 12, b = 10, c = 18

Explanation:
The decimal value of a as 12 is 12
The decimal value of b as 12(octal) is 10

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/difference-d-format-specifier-c-language/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide