Home » C++ programs

Define multiple Throw and Catch in C++ programming language

Exception Handling is very good feature with the help of this feature we can catch any thrown exception in the code. In this code snippet we will learn how to define multiple throw and catch statements in a single block in C++ Exception Handling.

Read more: Exception Handling in C++

Example: Multiple Throw and Catch Statement in C++ Exception Handling

/*Define multiple throw and catch statement in c++ - 
C++ Exception Handling Example.*/
 
#include <iostream>
 
using namespace std;
 
int main()
{
    int choice;
     
    try
    {
        cout<<"Enter any choice: "; 
        cin>>choice;
         
        if(choice == 0)         cout<<"Hello Baby!"<<endl;
        else if(choice == 1)    throw (100);    //throw integer value
        else if(choice == 2)    throw ('x');    //throw character value
        else if(choice == 3)    throw (1.23f);  //throw float value
        else    cout<<"Bye Bye !!!"<<endl;
    }
    catch(int a)
    {
        cout<<"Integer Exception Block, value is: "<<a<<endl;
    }
    catch(char b)
    {
        cout<<"Character Exception Block, value is: "<<b<<endl;
    }   
    catch(float c)
    {
        cout<<"Float Exception Block, value is: "<<c<<endl;
    }       
     
    return 0;
}

Output


    First Run:
    Enter any choice: 0
    Hello Baby!

    Second Run:
    Enter any choice: 1
    Integer Exception Block, value is: 100

    Third Run:
    Enter any choice: 2
    Character Exception Block, value is: x

    Fourth Run:
    Enter any choice: 3
    Float Exception Block, value is: 1.23

    Fifth Run:
    Enter any choice: 4
    Bye Bye !!!



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.