Category: python
Python Exception Handling
Published on 24 Jul 2026
Explanation
An exception is an error that occurs during the execution of a program. If exceptions are not handled properly, the
Code:
try:
number = int(input('Enter a number: '))
print('You entered:', number)
except ValueError:
print('Invalid input! Please enter a valid integer.')
print('Program completed successfully.')
Explanation
A program may encounter different types of exceptions depending on user input or runtime conditions. Python allows multiple except blocks
Code:
try:
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
result = num1 / num2
print('Result:', result)
except ValueError:
print('Please enter only numbers.')
except ZeroDivisionError:
print('Cannot divide by zero.')
print('End of Program')
Explanation
The finally block contains code that always executes, regardless of whether an exception occurs. It is commonly used to release
Code:
file = None
try:
file = open('sample.txt', 'r')
print(file.read())
except FileNotFoundError:
print('File not found.')
finally:
if file:
file.close()
print('File closed successfully.')
print('Program finished.')
Explanation
The raise statement allows developers to generate exceptions manually when a specific condition occurs. This is useful for validating input
Code:
def withdraw(balance, amount):
if amount > balance:
raise ValueError('Insufficient Balance')
balance -= amount
return balance
try:
remaining = withdraw(5000, 7000)
print('Remaining Balance:', remaining)
except ValueError as error:
print('Error:', error)
Explanation
Exception handling is widely used in real-world applications such as banking systems, web applications, APIs, and file processing programs. User
Code:
balance = 10000
try:
amount = float(input('Enter withdrawal amount: '))
if amount <= 0:
raise ValueError('Withdrawal amount must be greater than zero.')
if amount > balance:
raise ValueError('Insufficient balance.')
balance -= amount
print('Transaction Successful')
print('Remaining Balance:', balance)
except ValueError as error:
print('Error:', error)
finally:
print('Thank you for using our ATM.')