- __init__() function
- Aliases
- and operator
- argparse
- Arrays
- Booleans
- Break statement
- Bytes
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Context manager
- Data class
- Data structures
- Data visualization
- datetime module
- Decorator
- Dictionaries
- Docstrings
- Encapsulation
- enum
- enumerate() function
- Equality operator
- Error handling
- Exception handling
- False
- File handling
- Filter()
- Flask framework
- Floats
- Floor division
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Inheritance
- Integers
- Iterator
- Lambda function
- len() Function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List reverse() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Modulo operator
- Multiline comment
- Multiprocessing
- Multithreading
- None
- not operator
- NumPy library
- OOP
- or operator
- Override method
- Pandas library
- Parameters
- pathlib module
- Pickle
- Polymorphism
- print() function
- Property()
- Random module
- range() function
- Raw strings
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Script
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Type casting
- Variables
- Virtual environment
- While loops
- Zip function
PYTHON
Python Exception Handling: Syntax, Usage, and Examples
Python exception handling lets you catch and manage errors, preventing program crashes. Instead of stopping execution when an error occurs, Python gives you tools to handle issues gracefully and keep your code running smoothly.
How to Use Exception Handling in Python
You can use the try-except block to catch exceptions and execute alternative code. The basic syntax looks like this:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
try: Runs a block of code that might cause an error.except: Catches and handles the specified exception.ExceptionType: Defines the type of error to handle, such asZeroDivisionErrororFileNotFoundError.
A finally block ensures that specific code runs no matter what happens.
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("Execution complete.")
When to Use Exception Handling in Python
Preventing Program Crashes
If your program processes user input, files, or network requests, it must handle errors properly. Without exception handling, a single unexpected input can crash your entire application.
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("You must enter a number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
Handling Multiple Exceptions
You can catch different errors in a single try block using multiple except statements. This keeps your program running even when unexpected issues occur.
try:
data = open("file.txt", "r").read()
result = 10 / int(data)
except FileNotFoundError:
print("The file is missing.")
except ValueError:
print("The file contains non-numeric data.")
except ZeroDivisionError:
print("You cannot divide by zero.")
Logging Errors for Debugging
Instead of displaying errors to users, you can log them for debugging. The logging module lets you record exceptions in a structured way.
import logging
logging.basicConfig(filename="errors.log", level=logging.ERROR)
try:
with open("config.json", "r") as file:
config = file.read()
except FileNotFoundError as e:
logging.error(f"Error: {e}")
Examples of Exception Handling in Python
Catching All Exceptions
If you need to handle every possible error, catch Exception. Be cautious with this approach, as it hides specific errors, making debugging harder.
try:
result = 10 / 0
except Exception as e:
print(f"An error occurred: {e}")
Using else in Exception Handling
An else block runs only if no exceptions occur. This keeps your code organized and makes it clear what happens when errors don't occur.
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print(f"You entered: {number}")
Raising Custom Exceptions
You can create your own exceptions using raise. This helps you enforce rules in your program.
def check_age(age):
if age < 18:
raise ValueError("You must be 18 or older.")
print("Access granted.")
try:
check_age(16)
except ValueError as e:
print(e)
Learn More About Exception Handling in Python
Handling Multiple Exceptions in One Block
You can catch multiple exception types in a single except statement by using a tuple.
try:
num = int("abc")
result = 10 / num
except (ValueError, ZeroDivisionError):
print("Invalid operation.")
Using finally for Cleanup
A finally block runs whether an exception occurs or not. Use it for cleanup tasks like closing files or releasing resources.
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("Closing resources.")
Handling Nested Exceptions
If you run code inside loops or functions, you may need nested try-except blocks. This approach helps manage errors at different levels.
try:
for i in range(3):
try:
value = int(input(f"Enter a number for iteration {i}: "))
print(10 / value)
except ZeroDivisionError:
print("You cannot divide by zero.")
except KeyboardInterrupt:
print("Process interrupted.")
Logging Errors to a File
Logging errors instead of printing them keeps track of issues over time.
import logging
logging.basicConfig(filename="app.log", level=logging.ERROR)
try:
with open("data.csv", "r") as file:
content = file.read()
except FileNotFoundError as e:
logging.error(f"File error: {e}")
Python exception handling helps you prevent crashes, improve debugging, and write reliable applications. Exception handling ensures your program runs smoothly by handling user input errors, file access issues, or unexpected failures.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.