Output of Python Program | Set 8 (Exception Handling)
0 183
Output of Python Program | Set 8 (Exception Handling)
Exception handling is a crucial aspect of writing robust Python programs. It allows you to manage errors gracefully without crashing your program. In this blog, we'll explore various examples demonstrating how Python handles exceptions and what outputs you can expect from these programs.
Basic Try-Except Block
The simplest form of exception handling uses a try-except
block to catch and handle exceptions:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Here, attempting to divide by zero raises a ZeroDivisionError
, which is caught and handled by printing a message.
Catching Multiple Exceptions
You can catch multiple exceptions in a single except block by using a tuple:
try:
num = int("abc")
except (ValueError, TypeError):
print("Caught a ValueError or TypeError")
Output:
Caught a ValueError or TypeError
Using Else and Finally
The else
block executes if no exception occurs, while finally
runs regardless of exceptions:
try:
num = int("123")
except ValueError:
print("Conversion failed")
else:
print("Conversion succeeded:", num)
finally:
print("This will always execute")
Output:
Conversion succeeded: 123
This will always execute
Raising Exceptions
You can also manually raise exceptions using the raise
keyword:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18")
else:
print("Age is valid")
try:
check_age(15)
except ValueError as e:
print(e)
Output:
Age must be at least 18
Practice Problem
Write a Python program that asks the user to input a number and divides 100 by that number. Use exception handling to catch any errors like division by zero or invalid input, and print appropriate error messages.
# Practice Problem:
# Input a number from user and divide 100 by it
# Handle exceptions for invalid input and division by zero
try:
# Your code here
pass
except Exception as e:
print("Error:", e)
Solution to Practice Problem
try:
num = int(input("Enter a number to divide 100 by: "))
result = 100 / num
except ValueError:
print("Invalid input! Please enter an integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result is:", result)
This program prompts for user input, handles invalid inputs and division by zero gracefully, and outputs the result if no errors occur.
Summary
Exception handling helps make your Python programs more reliable by managing runtime errors. Using try-except
blocks, you can catch exceptions, clean up with finally
, and raise your own errors when necessary. Practice writing and handling exceptions to write better, more fault-tolerant code.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments