Py Assignment 8 S11 16
Py Assignment 8 S11 16
Theory:
Exception Handling Mechanism
Python provides the try-except block to handle runtime errors. The execution
flow is as follows:
The try block contains the code that may cause an exception.
Using try-except
It ensures that the program does not crash when an error occurs.
The else block runs only if no exceptions occur in the try block.
It is useful for executing code that should run only when there are no
errors.
while True:
try:
if c == 1:
r=a+b
print("Result:", r)
elif c == 2:
r=a-b
print("Result:", r)
elif c == 3:
r=a*b
print("Result:", r)
elif c == 4:
try:
r=a/b
print("Result:", r)
except ZeroDivisionError:
else:
if choice != 'yes':
break
except ValueError:
print("Invalid input. Please enter valid numbers.")
Output:
2. Celsius to Fahrenheit
print("Celsius to Fahrenheit Converter")
while True:
try:
continue
break
except ValueError:
while True:
try:
break
except ValueError:
if a == 1:
r = (t * 9/5) + 32
print("Result:", r, "°F")
elif a == 2:
r = (t - 32) * 5/9
print("Result:", r, "°C")
else:
print("Invalid input.")
Output:
3. Banking Interface:
print("Simple Banking Process")
balance = 20000
while True:
try:
choice = int(input("Enter \n 1. Withdraw \n 2. Deposit \n 3. Check Bank
Balance \n 4. Exit \n"))
if choice == 1:
if temp_balance < 0:
else:
balance = temp_balance
print("Amount withdrawn.")
elif choice == 2:
balance += amount
elif choice == 3:
elif choice == 4:
break
else:
except Exception:
finally:
Output:
Conclusion:
Exception handling in Python provides a robust mechanism for managing
runtime errors. Using try-except, else, finally, raise, and custom exceptions
ensures that programs run smoothly without unexpected crashes. This
approach enhances software reliability, improves user experience, and
makes debugging easier.