π§ What is an Exception?
- Sometimes, a program has an error while running.
- These errors are called exceptions.
- Example: Dividing a number by zero β this gives an error.
π§ͺ Example:
print(10 / 0)
π This gives an error: ZeroDivisionError
π― Why Use Exception Handling?
- To stop the program from crashing when error happens.
- We can show a friendly message instead.
π Keywords Used:
Keyword | Meaning (Simple) |
---|---|
try | Write risky code here |
except | What to do if error happens |
else | What to do if no error happens |
finally | Always do this, error or no error |
raise | You make your own error |
π Structure:
try:
# Your code
except:
# If error happens
else:
# If no error happens
finally:
# Always run this
π Real-Life Example:
- ATM machine:
- If you enter the wrong PIN β show error, donβt crash!
- Same in Python: If something goes wrong, show a message, not crash.
Examples :
1) Demo crash without handling:
num = int(input("Enter a number: "))
print(100 / num)
2) Using try-except
try:
num = int(input("Enter a number: "))
print(100 / num)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
3) else and finally
try:
num = int(input("Enter a number: "))
result = 100 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Result is:", result)
finally:
print("Execution complete.")
4) Handling Multiple Errors
try:
lst = [1, 2, 3]
index = int(input("Enter index: "))
print(lst[index])
except (IndexError, ValueError) as e:
print("Error:", e)
5) Custom Exceptions
age = int(input("Enter your age: "))
if age < 18:
raise Exception("You must be at least 18 years old.")
6) Creating Your Own Exception Class
class UnderAgeError(Exception):
pass
age = int(input("Enter age: "))
if age < 18:
raise UnderAgeError("You are under 18, not allowed!")
7) Get two inputs and safely divide them.
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Denominator cannot be zero!")
except ValueError:
print("Please enter valid numbers.")
8)Ask for an index and print item from a list.
fruits = ["apple", "banana", "cherry"]
try:
i = int(input("Enter index (0β2): "))
print("Fruit:", fruits[i])
except IndexError:
print("Index out of range.")
except ValueError:
print("Invalid input. Please enter a number.")
9) Raise exception if password is less than 6 characters.
try:
username = input("Username: ")
password = input("Password: ")
if len(password) < 6:
raise ValueError("Password too short! Must be at least 6 characters.")
print("Login successful.")
except ValueError as ve:
print("Error:", ve)
10) Age Verifier using Custom Exception
class AgeTooLowError(Exception):
pass
try:
age = int(input("Enter your age: "))
if age < 18:
raise AgeTooLowError("Access denied: You are under 18.")
else:
print("Access granted.")
except AgeTooLowError as e:
print(e)
except ValueError:
print("Please enter a valid number.")
11) Read a file. If not found, handle error.
try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
Leave a Reply