0% found this document useful (0 votes)
15 views

Exception Handling

Exceptional handling

Uploaded by

dkhokher21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Exception Handling

Exceptional handling

Uploaded by

dkhokher21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Exception Handling in OOP

What is Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions. Exceptions can be caused by various issues such as incorrect user input,
unavailable resources, or logical errors in the code.
Where to Use Exceptions?
1. User Input Validation: When the user provides invalid data.
2. File Operations: When trying to read from or write to a file that may not exist or may be
inaccessible.
3. Network Operations: When performing network communications, such as downloading a
file, which might fail due to connectivity issues.
4. Database Operations: When interacting with a database, exceptions can handle issues like
unavailable connections or query failures.
5. Resource Management: When handling resources that need to be cleaned up properly,
such as closing files or releasing memory.
Sections of the Exception Handling?

Throw Statement:

• The throw statement explicitly generates an exception.


• It signals an error and transfers control to the nearest catch block.

Try Block:

• The try block contains code that may throw an exception.


• It allows the program to test for errors while executing a block of code.

Catch Block:

• The catch block handles exceptions thrown by the try block.


• It defines the response and recovery actions when an error occurs.

Program Example without Exception Handling that stop program execution unexpectedly
when divide by 0.
#include <iostream>
using namespace std;
int div(int a, int b)
{

return a/b;
}

int main(int argc, char** argv) {


int num1,num2;
cout<<"Enter two numbers to divide"<<endl;
cin>>num1>>num2;
int r=div(num1,num2);
cout<<r;
return 0;
}
Program Example where exception handling is used where divide by 0 is managed.
#include <iostream>
using namespace std;
int div(int a, int b)
{
if(b==0)
throw 0;
return a/b;
}

int main(int argc, char** argv) {


int num1,num2;
cout<<"Enter two numbers to divide"<<endl;
cin>>num1>>num2;
try
{

int r=div(num1,num2);
cout<<r;
}
catch (int n)
{
cout<<" can not divide by Zero";}

return 0;
}

You might also like