Introduction
- Exception handling is an OOPs concept of Python.
Definition
- An exception is an error that occurs during program execution or run time.
Characteristics
- Exception handling in Python is a mechanism used to handle runtime errors (exceptions) so that the normal flow of a program is not interrupted. Instead of crashing, the program can respond gracefully by handling an exception.
Advantages or Need of Exception Handling
- It prevents abnormal program crashes or termination.
- It improves program reliability.
- It separates error-handling code from normal code.
- It helps in debugging and maintenance.
-
It improves program robustness.
-
It helps in error recovery.
-
It makes code cleaner and more readable.
Elements of Exception Handling
- Exception handling in Python uses try, except, else, finally, and raise keywords to manage runtime errors effectively, ensuring smooth program execution.
- The following major elements are used to catch and handle exceptions that arise suddenly.
- try block
- except block
- else block
- This block is used mainly when no exception occurs. eg-
-
- raise block
- This block is used to raise custom or predefined exceptions.
- For example –
- raise block
-
- finally block
-
This block is used to execute whether an exception occurs or not.
-
It is used for cleanup operations.
- For example –
-
- finally block
-
- User-Defined (Custom) Exceptions
- This exception type is used to create our own or customized exception class.
- For example –
- User-Defined (Custom) Exceptions
Syntax
Example
Built-in Exceptions in Python
Some common Built-in Exceptions of Python are –
Exception Type Name – Description
- ZeroDivisionError – Division by zero
- ValueError – Invalid value
- TypeError – Wrong data type
- IndexError – Index out of range
- KeyError – Dictionary key missing
- FileNotFoundError – File not found
======================= XXX ========================
Program Examples on Exception Handling
Example: A Python program to handle multiple exceptions.
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input! Enter integers only")
![]()
0 Comments