Introduction to Exceptions
What is an Exception
An exception is an error that occurs during the execution of a program. When an exception occurs, the program stops unless it is handled properly.
Example
print(10 / 0) # ZeroDivisionError
Types of Errors
- Syntax Errors (compile-time errors)
if True
print("Hello") # Missing colon
- Runtime Errors (exceptions)
x = int("abc") # ValueError
Common Built-in Exceptions
ZeroDivisionErrorValueErrorTypeErrorIndexErrorKeyError
Importance of Exception Handling
- Prevents program crashes
- Improves user experience
- Helps debugging
- Ensures smooth program flow
- try, except Block
Structure
try:
# code that may cause error
except:
# code to handle error
//Handling Single Exception
try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid input")
//Handling Multiple Exceptions
try:
a = int(input())
b = int(input())
print(a / b)
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")
//Generic Exception
try:
x = int("abc")
except Exception as e:
print("Error:", e)
Best Practices
- Catch specific exceptions first
- Avoid using only generic
except - Keep try block small
- Provide meaningful error messages
- else and finally Block
else Block
//Executes if no exception occurs.
try:
num = int("10")
except ValueError:
print("Error")
else:
print("Success:", num)
//finally Block
//Always executes, whether an exception occurs or not.
try:
file = open("test.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")
Execution Flow
- try block executes
- If exception occurs → except block runs
- If no exception → else block runs
- finally block always runs
Real-World Example
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
else:
print(content)
finally:
print("Closing program")
- Custom Exceptions
Custom exceptions allow you to define your own error types.
//Creating Custom Exception
class MyError(Exception):
pass
//Raising an Exception
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above")check_age(16)
//Using Custom Exception
class InvalidAgeError(Exception):
passdef validate(age):
if age < 18:
raise InvalidAgeError("Not eligible")try:
validate(15)
except InvalidAgeError as e:
print(e)
Best Practices
- Use meaningful names
- Extend from
Exceptionclass - Use for specific application logic
Conclusion
Exception handling is a vital part of Python programming that ensures programs run smoothly even when errors occur. By using try, except, else, and finally blocks, developers can manage errors effectively and improve program reliability.
Custom exceptions further enhance flexibility by allowing developers to define their own error conditions. Mastering exception handling helps in building robust, user-friendly, and professional applications.
Understanding and applying these concepts prepares learners for real-world programming, where handling unexpected situations is essential for success.
Leave a Reply