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")
Example : A Python program to handle Invalid Input Exceptions.
try:
num = int(input("Enter an integer: "))
print("You entered:", num)
except ValueError:
print("Error: Invalid input, enter integers only")
Output:
Enter an integer: hhh
Error: Invalid input, enter integers only
Example : A Python program to handle Specific Exceptions.
try:
f = open("sample.txt", "r")
print(f.read())
except FileNotFoundError:
print("Error: File does not exist")
-------------- OR --------------
try:
arr = [10, 20, 30]
print(arr[5])
except IndexError:
print("Index out of range")
-------------- OR --------------
try:
d = {"name": "Ravi", "age": 20}
print(d["marks"])
#print(d["age"])
except KeyError:
print("Key not found in dictionary")
-------------- OR --------------
try:
result = "10" + 5
except TypeError:
print("Type mismatch error")
Example : A Python program to handle All/General Exceptions.
try:
x = int("abc")
except Exception as e:
print("Error:", e)
Output:
Error: invalid literal for int() with base 10: 'abc'
-------------- OR --------------
try:
x = int("10.23")
except Exception as e:
print("Error:", e)
Output:
Error: invalid literal for int() with base 10: '10.23'
-------------- OR --------------
try:
x = (10.23+"abc")
except Exception as e:
print("Error:", e)
Output:
Error: unsupported operand type(s) for +: 'float' and 'str'
![]()
0 Comments