Python Exception Handling
In the previous lesson, we learned about Strings and how they are used to store and manipulate text in Python. Today, we will learn about Exception Handling, which helps programs handle errors gracefully without crashing.
Exception Handling is very important because errors can occur during program execution, especially when dealing with user input, files, or calculations.
What is an Exception?
An Exception is an error that occurs while a program is running.
When an exception occurs, Python stops the program and displays an error message.
Example
number = 10 / 0
print(number)
Output
ZeroDivisionError: division by zero
Why Exception Handling is Important
Exception Handling helps programmers:
- Prevent program crashes
- Handle unexpected errors
- Improve user experience
- Make programs more reliable
- Debug applications easily
The try and except Block
Python uses:
- "try"
- "except"
to handle exceptions.
Syntax
try:
# risky code
except:
# code to handle error
Example of try and except
try:
number = 10 / 0
print(number)
except:
print("An error occurred")
Output
An error occurred
Instead of crashing, the program handles the error gracefully.
Handling Specific Exceptions
Python allows handling specific error types.
Example
try:
number = int(input("Enter a number: "))
print(number)
except ValueError:
print("Invalid input")
Sample Output
Enter a number: abc
Invalid input
Common Python Exceptions
Exception| Meaning
"ValueError"| Invalid value
"TypeError"| Wrong data type
"NameError"| Variable not defined
"IndexError"| Invalid index
"KeyError"| Invalid dictionary key
"ZeroDivisionError"| Division by zero
"FileNotFoundError"| File does not exist
The else Block
The "else" block runs if no exception occurs.
Example
try:
number = int(input("Enter a number: "))
print(number)
except ValueError:
print("Invalid input")
else:
print("Program executed successfully")
The finally Block
The "finally" block always executes whether an error occurs or not.
Example
try:
print("Python")
except:
print("Error")
finally:
print("Execution completed")
Output
Python
Execution completed
Using Multiple Exceptions
A program can handle multiple exceptions.
Example
try:
number = int(input("Enter number: "))
result = 10 / number
print(result)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
Raising Exceptions
Python allows programmers to create custom exceptions using "raise".
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output
ValueError: Age cannot be negative
Simple Calculator with Exception Handling
Example
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result =", result)
except ValueError:
print("Please enter valid numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
Advantages of Exception Handling
Exception Handling makes programs:
- More secure
- More stable
- Easier to maintain
- User-friendly
- Better at handling unexpected situations
Most real-world applications use Exception Handling extensively.
Conclusion
Exception Handling is an essential concept in Python programming because it allows programs to handle errors smoothly without crashing.
Understanding "try", "except", "else", and "finally" helps programmers build professional and reliable applications.
Practice handling different exceptions to improve your Python programming skills.
Top comments (0)