Exception Handling
Exception Handling
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:
Try Block:
Catch Block:
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 r=div(num1,num2);
cout<<r;
}
catch (int n)
{
cout<<" can not divide by Zero";}
return 0;
}