More About Catch in C++


In the code, a float value 1.8f is thrown using the throw statement. The try block is used to catch the thrown exception. There are three catch blocks provided to catch exceptions of different types:

  • The first catch block catches int type exception. However, since the exception thrown is of type float, this block will not execute.
  • The second catch block catches float type exception. Since the exception thrown is of type float, this block will execute and the output will be "Float Catch : 1.8".
  • The third catch block is a catch-all block and will execute if none of the previous catch blocks match the type of the thrown exception. In this case, this block will not execute.

After the catch blocks, "End" will be printed to the console.

Source Code

#include<iostream>
using namespace std;
int main()
{
    try
    {
        throw 1.8f;
    }
    catch(int e)
    {
        cout<<"Integer Catch : "<<e<<endl;
    }
    catch(float e)
    {
        cout<<"Float Catch : "<<e<<endl;
    }
    catch(...)
    {
        cout<<"All Catch : "<<endl;
    }
    cout<<"End";
    return 0;
}
To download raw file Click Here

Output

Float Catch : 1.8
End

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples