Try Catch Function Example in C++


This code defines a function division that takes two integers x and y, and returns the result of dividing x by y. If y is 0, then it throws an exception of type int with value 1. In the main function, it calls division with arguments a=10 and b=2. If division succeeds, it prints the value of c (which is a/b). If division throws an exception, it catches the exception and prints an error message. Finally, it prints "End" and returns 0.

Source Code

//Try Catch Between Function
#include<iostream>
using namespace std;
int division(int x,int y)
{
    int z;
    if(y==0)
        throw 1;
    z=x/y;
    return z;
}
int main()
{
    int a=10,b=2,c;
    try
    {
        c=division(a,b);
        cout<<"The Value of C : "<<c<<endl;
    }
    catch(int e)
    {
        cout<<"Error Dividing by Zero"<<endl;
    }
    cout<<"End";
    return 0;
}
To download raw file Click Here

Output

The Value of C : 5
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