Click for All Topics
Exception handling is utilized in programming to effectively manage and respond to unexpected errors or exceptional situations that may arise during the execution of a program.
These situations can disrupt the normal flow of a program and cause it to terminate abruptly.
Example –
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a number.")
else:
print("Result:", result)
finally:
print("Execution complete.")
# Output
# Enter a number: 0
# Error: Division by zero!
# Execution complete.
Explanation:
try
block the code is written to obtain user input and perform a division operation.ZeroDivisionError
occurs, the corresponding except block will be executedValueError
occurs, the corresponding except block will be executedelse
block will get executedfinally
will get executed at the end.
try
, except
, else
, and finally
in handling errors in programming:
💡Note: Without the try block, the program will fail to operate and generate an error.
except ZeroDivisionError:
print("Error: Division by zero!")
else:
print("Result:", result)
finally:
print("Execution complete.")
# Output -
# File "/home/main.py", line 1
# except ZeroDivisionError:
# ^^^^^^
# SyntaxError: invalid syntax
try
block and specifies how the program should handle specific types of exceptions. If an exception occurs within the try
block and it matches the type specified in the except
block, the code inside the except
block is executed.
a. Try-Except
#The try block will generate an exception, because y is not defined:
try:
print(y)
except:
print(" exception ")
# Output -
# exception
b. Many Exceptions:
You have the flexibility to define multiple exception blocks as needed, allowing you to execute specific code for distinct types of errors.
Example –
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a number.")
# Output -
# Enter a number: 0 1 a
# Error: Invalid input. Please enter a number.
else
block is optional and comes after the try
and except
blocks. It’s executed when no errors occur in the try
block. This is where you can put code that should run if everything goes smoothly.
Example –
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a number.")
else:
print("Result:", result)
# Output -
# Enter a number: 20
# Result: 0.5
finally
block is also optional and appears after the try
and except
blocks. It gets executed regardless of whether an error occurred or not. It’s useful for tasks that need to be done no matter what, like closing a file or releasing resources.
a. Try-except-else-finally:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a number.")
else:
print("Result:", result)
finally:
print("Execution complete.")
# Output -
# Enter a number: 2
# Result: 5.0
# Execution complete.
b. Try-except-finally:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter a number.")
finally:
print("Execution complete.")
# Output -
# Enter a number: b
# Error: Invalid input. Please enter a number.
# Execution complete.
An error refers to a situation where the code you’ve written cannot be executed as expected due to various reasons.
Note: An error in Python refers to a situation where something goes wrong during the execution of your code where as an exception in Python is a specific type of error that occurs during the execution of your code and disrupts the normal flow of the program.
💡Why it is called exception handling and not error handling?
Exception handling is specifically called that way because it focuses on handling exceptional situations or events that occur during the execution of a program, rather than just general errors. While errors are a subset of exceptions, not all exceptions are necessarily errors.
The raise
statement is like you telling the computer, “Okay, now I want this specific problem to happen!” It’s a way for you to make your program show a certain error or issue on purpose.
“Raising an exception” means you’re making your program stop and say, “Hey, something’s not right!“.
Here’s a simple example:
Imagine you’re making a robot that serves drinks. If someone asks for a drink that the robot doesn’t know, you want the robot to say, “I don’t have that drink.” That’s like raising an exception. You’re telling the robot, “Hey, this isn’t right, let’s handle it!”
Code –
drink_menu = ['water', 'soda', 'juice']
def serve_drink(choice):
if choice not in drink_menu:
raise Exception("I don't have that drink.")
else:
print("Here's your", choice)
user_choice = input("Please choose a drink: ")
try:
serve_drink(user_choice)
except Exception as e:
print("Sorry, an error occurred:", e)
# Output -
# Please choose a drink: wine
# Sorry, an error occurred: I don't have that drink.
Explanation:
serve_drink
function raises an exception.except
block, which handles the situation and gives an error message.
Advantages of Exception Handling | Disadvantages of Exception Handling |
---|---|
Effective error management | Increased code complexity |
Facilitates debugging | Overuse leading to unclear control flow |
Improves user experience | May hide underlying issues |
Provides controlled program flow | Complicates debugging |
Encourages modular code | Dependency on documentation |
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India