C++ Exception Handling

21 September, 2018

Related Blogs

Exception Handling

Exceptions are unusual conditions in a program.

They may cause the programs to fail or may lead to errors. They must be deal with.

There are 2 types of exceptions in C++

synchronous and asynchronous

“out-of- range index” and “over –flow” are synchronous type.

Errors caused by the events beyond the central of the program like keyboard interrupts are called asynchronous interrupts.

Exception is a logical error

Exception is an error which occur during runtime (Because Invalid input)


Exceptions Example in C++

# include <iostream.h> int main() { int n1,n2; cout<<”Input any 2nos”; cin >>n1>>n2; n3=n1/n2; cout<<n3; } try catch &throw (not recognized turbo c++3.0)  

Purpose of  C++ Exception  Handling

The purpose of exceptional handling in C++  is to defect and report an “exceptional circumstance.

Then appropriate action can be taken.

The error handling code basically consists of two segments.

One to detect errors and to throw exceptions.

The other to catch the exceptions and to take appropriate action.


Structure of Try block in C++

This block contain code which has to be monitored for exception handling.

This block contain condition or business block

try { statements; throw exception-type; }

Structure of Catch block in C++

This block contain error logic.

Exception thrown by try block handled by using catch block.

catch (exception-type var) { statements; }  

Example of C++ Exception Handling

# include <iostream.h> void main() { int n1,n2,n3; clrscr(); cout<<”\n Input any two numbers”; cin >> n1>>n2; try { if (n2==0) throw 0; (is type of int) else n3=n1/n2; } catch (int x) { cout<<”\n cannot divide number with zero”; } }   Example of Exception Handling in C++ # include <iostream.h> # include<conio.h> # include<string.h> class login-exception { }; void Main() { char uname[10],password [10]; login –exception invalid –login; cout<<”\n Input usernamr”; cin>>uname; cin >>password; try { if (strcmp (uname,”nit”)==0&& strcmp (password ,”nit”); cout <<”\n Welcome to my app”; else throw invalid _login; } catch(login_exception e) { cout<<”\n Invalid username or password”; }}