**Definition of Exception**: An exception is an unexpected problem that arises during the
execution of a program, leading to sudden termination due to errors. Examples include
division by zero, accessing an array out of bounds, running out of memory, and running out
of disk space.
## Types of Exceptions
- **Synchronous Exceptions**: Occur during program execution due to faults in input data,
such as division by zero or overflow.
- **Asynchronous Exceptions**: Caused by external events beyond the program's control,
like hardware failures.
## Exception Handling Mechanism
- **Purpose**: To handle synchronous exceptions gracefully, allowing the program to
continue running without errors.
- **Responsibilities**:
1. Detect the problem (throw the exception).
2. Inform that an error has been detected.
3. Receive error information (catch the exception).
4. Take corrective action (handle the exception).
## Keywords in Exception Handling
- **try**: Defines a block of code that may throw an exception.
- **throw**: Used to signal that an exception has occurred.
- **catch**: Defines a block of code that handles the exception thrown from the try block.
## Flow of Control
- If no exception is thrown, the program continues execution.
- If an exception is thrown, the try block exits, and the program searches for a matching
catch block.
## User-Defined Exceptions
- **Creating Custom Exceptions**: Users can define their own exception classes derived
from the standard exception class, allowing for more context-specific error handling.
- **Throwing and Handling**: Custom exceptions can be thrown and caught similarly to
standard exceptions.
, ## Processing Unexpected Exceptions
- If an exception is thrown but not caught, the `unexpected()` function is called, which by
default terminates the program.
## Exception and Inheritance
- When catching exceptions from base and derived classes, the derived class catch block
must precede the base class catch block to ensure proper handling.
## Example Programs
- Demonstrations of exception handling include division by zero and generating exceptions
through user-defined functions.
1. Explain try, catch, and throw keywords in exception handling mechanism.
In C++ (or similar languages), exception handling is used to manage errors during program
execution. It allows the program to handle unexpected situations without crashing.
1. try block:
This block contains code that might throw an exception.
If an error occurs, the control jumps to the catch block.
Example:
try {
// risky code
}
2. throw keyword:
It is used to throw an exception when an error occurs.
It sends the exception to the nearest catch block.
Example:
throw 10; // throwing an integer exception
3. catch block:
This block handles the exception thrown by throw.
It must follow the try block.
Example:
catch(int e) {
cout << "Caught exception: " << e;
}