Exception Handling in C++

In C++ programming, an exception is an abnormal condition that arises/occurs in a source code during run time.  

Or

 Exception is a run time error.  

Example:

Output

When we try to compile this program we will receive an error message because value of 100/a (100/0) is infinite and it can’t be possible to save and print infinite value.    

Handle Exception in C++

In a C++ programming language whenever an exceptional condition is arises it can be handled by the three keywords: try, catch and throw.

The Keyword try:  Any code or statement that we want to monitor for an exception must be put inside the try block.

Syntax for try block:

   Example:  

In an above statement we have written try block.

Inside the try block we have placed a code (b=100/a) in which exception may occur.

Value of “ a” can be any integer value there is no problem but if the value of variable “a” is  zero then error will generate because  100/a (100/0) is infinite and it can’t be possible to save and print infinite value.             

The Keyword throw: If the exception occurs within try block it is automatically thrown by system or it can be manually thrown by using “throw” keyword. Syntax for throw:

throw    (excep);    

when excep is throw catch statement associated with the try block is handle this exception.

The Keyword catch: When the exceptional condition is arises within the try block it is thrown by the keyword throw and catch by the catch statement associated with the try block.

 Syntax for catch block:

Note: If there is no exception within the try block then catch block will never execute.

Example:   Write a program to show exception.

Output

 
Calling show method of Shape
Shape is no defined
Calling show method of Circle
Showing a Circle
Calling show method of Rectangle
Showing a Rectangle
Calling show method of Square
Showing a Square
Calling show method of Triangle
Showing a Triangle

 Example:   Write a program to throw an exception when a =0 otherwise perform division.

Output

Example:   Write a program to throw an exception when a =1 otherwise perform subtraction of x and y.

Output

Multiple Catch Block

In a C++ programming we can define multiple catch statement for a single try block. Syntax for multiple catch is:  

Example:   Write a program to throw multiple exception and defined multiple catch statement.

Output

Default catch()

In a C++ exception handling  it is also possible to define single or default catch block for one or more exception of different types.

In such a situation, a single catch block can  catch exception thrown by multiple throw statement.  

Example:   Write a program to throw multiple exception and defined multiple catch statement.

Output

Categories C++