Fdocuments - in Exception Handling in C 58bcee0564d59
Fdocuments - in Exception Handling in C 58bcee0564d59
If a Smartphone
fails the test
catch
to n
d
sen ctio
Re odu
pr
IMPORTANT POINTS
When a try block end it must be followed by a catch block.
If we write catch block but don’t write try block then the program
will show
If we don’t write try and catch but write throw then the program
will build and run but it will show run time error.
#include<iostream>
main()
{
std::cout<<"welcome";
throw 10;
return 0;
}
TRY BLOCK
In an program a block of code which can produce error is
placed in try block
When an exception is detected in try it is thrown using
throw statement
Syntax
try
{
throw exception;
}
catch(type argument)
{
}
#include<iostream>
using namespace std;
main()
{
int a,b;
cout<<"enter values of a and b\n";
cin>>a;
cin>>b;
int x=a-b;
try{
if (x!=0)
{
cout<<"result(a/x)="<<a/x<<"\n";
}
else{
throw(x);
}
}
catch(int i)
{
cout<<"exception
caught:x="<<x<<"\n";
}
cout<<"end";
return 0;
}
THROWING MECHANISM
An exception is thrown using the throw statement in one of the
following ways
throw(exception);
throw exception;
throw;
o We can add use multiple throw statements by using if – else
statement
e.g.
int i=3;
Try {
if(i==1)
throw 1;
if(i==2)
throw 2;
}
CALL THROW USING FUNCTION
#include<iostream>
using namespace std;
void fun() fun function
contains throw
{
throw 3;
}
int main()
{
int i=3;
try{
if (i=3)
In try instead of writing throw
fun();
fun function is calling throw
}
catch(int e){
cout<<"\n exception no:"<<e;
}
cout<<"\n throw successfully called by
function";
getch();
}
CATCHING MECHANISM