0% found this document useful (0 votes)
5 views

Py Assignment 8 S11 16

The document explains exception handling in Python, detailing the use of try-except blocks, else, and finally for managing runtime errors. It includes examples of a basic calculator, a temperature converter, and a simple banking interface to illustrate the concepts. The conclusion emphasizes the importance of exception handling for software reliability and user experience.

Uploaded by

pranshu07d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Py Assignment 8 S11 16

The document explains exception handling in Python, detailing the use of try-except blocks, else, and finally for managing runtime errors. It includes examples of a basic calculator, a temperature converter, and a simple banking interface to illustrate the concepts. The conclusion emphasizes the importance of exception handling for software reliability and user experience.

Uploaded by

pranshu07d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

8. Exception handling in Python: LO1,LO5


Aim:
To demonstrate exception handling in python

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.

 If an exception occurs, the except block catches and handles it.

 If no exception occurs, the else block (if present) executes.

 The finally block runs regardless of whether an exception occurs,


making it useful for cleanup tasks like closing files.

Using try-except

 This is the most basic form of exception handling.

 It ensures that the program does not crash when an error occurs.

 Multiple except blocks can be used to handle different exceptions


separately.

Using else in Exception Handling

 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.

Using finally for Cleanup Operations


 The finally block always executes, regardless of whether an exception
occurs or not.

 It is typically used for resource cleanup, such as closing files or


database connections.

Raising Exceptions Using raise

 The raise statement is used to generate custom exceptions manually.

 It is useful when specific conditions require stopping program


execution with a meaningful error message.

Creating Custom Exceptions

 Python allows defining custom exception classes by inheriting from the


Exception class.

 Custom exceptions help in handling specific error cases in a structured


way.

Program with output:


1. Basic Calculator:
print("Basic Calculator")

while True:

try:

a = int(input("Enter 1st number: "))

b = int(input("Enter 2nd number: "))

print("\n1. Addition \n2. Subtraction \n3. Multiplication \n4. Division")


c = int(input("Enter your choice: "))

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:

print("Arithmetic error: Cannot divide by zero.")

else:

print("Invalid input, please try again.")

choice = input("Do you want to perform another operation? (yes/no):


").strip().lower()

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:

a = int(input("Enter \n 1 for Celsius → Fahrenheit \n 2 for Fahrenheit →


Celsius \nChoice: "))

if a not in [1, 2]:

print("Invalid input. Please try again.")

continue

break

except ValueError:

print("Invalid input. Please try again.")

while True:

try:

t = float(input("Enter Value: "))

break

except ValueError:

print("Invalid input. Please try again.")

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:

amount = int(input("Enter amount to withdraw: "))

temp_balance = balance - amount

if temp_balance < 0:

print("Withdraw amount exceeds balance. Transaction cancelled.")

else:

balance = temp_balance

print("Amount withdrawn.")

elif choice == 2:

amount = int(input("Enter amount to deposit: "))

balance += amount

print("Money has been deposited.")

elif choice == 3:

print("Current bank balance: ", balance)

elif choice == 4:

break

else:

print("Invalid input. Please try again.")


except ValueError:

print("Invalid input. Please enter a valid number.")

except Exception:

print("There was some error. Please try again.")

finally:

print("Thank you for banking with us.")

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.

You might also like