Exception Handling in C++
Exception Handling in C++
The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful feature of C++ to handle run time error and maintain normal flow of C++ application.
Exception
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions.
Handling the Exception
Handling the exception is nothing but converting system error message into user friendly error message. Use Three keywords for Handling the Exception in C++ Language, they are;
- try
- catch
- throw
Syntax for handling the exception
Example of Exception Handling in C++
try { // causes executions code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block }
Try Block
It is one of the block in which we write the block of statements which causes executions at run time in other words try block always contains problematic statements.
Catch block
It is one of the block in which we write the block of statements which will generates user friendly error messages in other words catch block will suppose system error messages.
Example without Exception Handling
Example
#include<iostream.h> #include<conio.h> void main() { int a, ans; a=10; ans=a/0; cout<<"Result: "<<ans; }
Output
Abnormally terminate program
Example of Exception Handling
Example
#include<iostream.h> #include<conio.h> void main() { int a=10, ans=0; try { ans=a/0; } catch(int i) { cout<<"Denominator not be zero"; } }
Output
Denominator not be zero