🧩 What isException Handling?
• An exception is an error that occurs while your code
is running — for example, dividing by zero or trying
to open a file that doesn’t exist.
• Instead of letting your program crash, exception
handling lets you catch and handle those errors
gracefully.
2.
🧱 Basic Syntax
•try:
• # code that may cause an error
• except:
• # code that runs if an error occurs
3.
🧠 Example 1— Basic
Try/Except
• try:
• num = int(input('Enter a number: '))
• result = 10 / num
• print('Result:', result)
• except:
• print('Something went wrong!')
• If the user enters 0 → ZeroDivisionError
• If the user enters a letter → ValueError
• The except block catches both and prevents crashing.
4.
🧱 Example 2— Handling
Specific Exceptions
• try:
• num = int(input('Enter a number: '))
• result = 10 / num
• print('Result:', result)
• except ValueError:
• print('❌ Please enter a valid number.')
• except ZeroDivisionError:
• print('❌ Cannot divide by zero.')
5.
🧱 Example 3— Using else and finally
• try:
• num = int(input('Enter a number: '))
• result = 10 / num
• except ZeroDivisionError:
• print('Division by zero is not allowed.')
• else:
• print('Result is:', result)
• finally:
• print('Program execution complete.')
• else → runs if no exception occurs
• finally → always runs (cleanup code)
6.
Real time Example- Finally
•Closing files
•Releasing resources
•Disconnecting from databases
•Ending network connections
7.
🧱 Example 4— Raising Your
Own Exception
• age = int(input('Enter your age: '))
• if age < 0:
• raise ValueError('Age cannot be negative.')
• print('Your age is:', age)
8.
🧱 Example 5— Custom
Exception Class (Advanced)
• class InvalidAgeError(Exception): //user-defined exception class
• pass
• try:
• age = int(input('Enter age: '))
• if age < 0:
• raise InvalidAgeError('Age cannot be negative.')
• except InvalidAgeError as e:
• print('Custom Error:', e)
9.
✅
Summary
Keyword Purpose
try Codethat might
throw an error
except Handles the error
else Runs if no error
occurs
finally Always runs
(cleanup code)
raise Manually raise an
exception