codescracker


c++

C++ Exception Handling



«Previous Chapter Next Tutorial »


An exception handling is a process to handle an exception that can be occurred in a program. Exceptions simply provides a way to transfer control from one part of program to another part of the program.

C++ exception handling is built upon the three keywords given here:

Here is the syntax to use try/catch block:

try
{
   // protected code
}catch(ExceptionName exc1)
{
   // catch block
}catch(ExceptionName exc2)
{
   // catch block
}catch(ExceptionName excN)
{
   // catch block
}

C++ Exception Handling Example

Here is an example program illustrating the concept of exception handling in C++ practically:

/* C++ Exception Handling - Example Program */

#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int num;
	cout<<"Enter a number: ";
	cin>>num;
	cout<<"Before try\n";
	try
	{
		cout<<"Insice try\n";
		if(num<0)
		{
			throw num;
			cout<<"After throw (never executed)\n";
		}
	}catch(int num)
	{
		cout<<"Exception caught\n";
	}
	cout<<"After catch (will be executed)\n";
	getch();
}

Here is the sample run of the above C++ program:

Enter a number: -1
Before try
Inside try
Exception caught
After catch (will be executed)

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test