Python Exception Handling Examples
Error handling is an important part of building robust programs. In Python, you can manage exceptions using try, except, finally, and more. These examples help beginners practice catching and managing errors gracefully.
1. Basic try-except block
1. Basic try-except block
python
try:
print(10 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
try:
print(10 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
2. Handling multiple exceptions
2. Handling multiple exceptions
python
try:
x = int("abc")
except ValueError:
print("Invalid integer conversion")
except TypeError:
print("Type error occurred")
try:
x = int("abc")
except ValueError:
print("Invalid integer conversion")
except TypeError:
print("Type error occurred")
3. Using else with try-except
3. Using else with try-except
python
try:
num = int("123")
except ValueError:
print("Conversion failed")
else:
print("Conversion successful:", num)
try:
num = int("123")
except ValueError:
print("Conversion failed")
else:
print("Conversion successful:", num)
4. try-except-finally
4. try-except-finally
python
try:
result = 10 / 2
except ZeroDivisionError:
print("Division error")
finally:
print("This always runs")
try:
result = 10 / 2
except ZeroDivisionError:
print("Division error")
finally:
print("This always runs")
5. Catching all exceptions
5. Catching all exceptions
python
try:
open("nonexistent.txt")
except Exception as e:
print("An error occurred:", e)
try:
open("nonexistent.txt")
except Exception as e:
print("An error occurred:", e)
6. Raise an exception manually
6. Raise an exception manually
python
age = -1
if age < 0:
raise ValueError("Age can't be negative")
age = -1
if age < 0:
raise ValueError("Age can't be negative")
7. Custom exception class
7. Custom exception class
python
class MyError(Exception):
pass
raise MyError("This is a custom error")
class MyError(Exception):
pass
raise MyError("This is a custom error")
8. Handling IndexError
8. Handling IndexError
python
try:
items = [1, 2]
print(items[5])
except IndexError:
print("Index out of range")
try:
items = [1, 2]
print(items[5])
except IndexError:
print("Index out of range")
9. Handling FileNotFoundError
9. Handling FileNotFoundError
python
try:
with open("missing.txt") as f:
content = f.read()
except FileNotFoundError:
print("File not found")
try:
with open("missing.txt") as f:
content = f.read()
except FileNotFoundError:
print("File not found")
10. Nested try-except blocks
10. Nested try-except blocks
python
try:
try:
x = 1 / 0
except ZeroDivisionError:
print("Inner block: Division by zero")
except:
print("Outer block")
try:
try:
x = 1 / 0
except ZeroDivisionError:
print("Inner block: Division by zero")
except:
print("Outer block")
11. Using pass in except
11. Using pass in except
python
try:
5 / 0
except ZeroDivisionError:
pass
print("Program continues...")
try:
5 / 0
except ZeroDivisionError:
pass
print("Program continues...")
12. Try-finally without except
12. Try-finally without except
python
try:
print("Trying something")
finally:
print("Cleanup code runs always")
try:
print("Trying something")
finally:
print("Cleanup code runs always")
13. ValueError handling
13. ValueError handling
python
try:
number = int("xyz")
except ValueError:
print("That's not a valid number")
try:
number = int("xyz")
except ValueError:
print("That's not a valid number")
14. AttributeError example
14. AttributeError example
python
try:
x = 10
x.append(5)
except AttributeError as e:
print("Attribute error:", e)
try:
x = 10
x.append(5)
except AttributeError as e:
print("Attribute error:", e)
15. TypeError handling
15. TypeError handling
python
try:
print("5" + 5)
except TypeError:
print("Can't add string and integer")
try:
print("5" + 5)
except TypeError:
print("Can't add string and integer")
16. KeyError in dictionary
16. KeyError in dictionary
python
try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("Key not found")
try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("Key not found")
17. ImportError handling
17. ImportError handling
python
try:
import nonexistingmodule
except ImportError:
print("Module not found")
try:
import nonexistingmodule
except ImportError:
print("Module not found")
18. Finally for resource cleanup
18. Finally for resource cleanup
python
try:
f = open("somefile.txt", "r")
except FileNotFoundError:
print("File missing")
finally:
print("Closing file (if opened)")
try:
f = open("somefile.txt", "r")
except FileNotFoundError:
print("File missing")
finally:
print("Closing file (if opened)")
19. Using assertions
19. Using assertions
python
x = 0
assert x > 0, "x must be greater than 0"
x = 0
assert x > 0, "x must be greater than 0"
20. Re-raising an exception
20. Re-raising an exception
python
try:
raise ValueError("Something went wrong")
except ValueError as e:
print("Caught error:", e)
raise
try:
raise ValueError("Something went wrong")
except ValueError as e:
print("Caught error:", e)
raise
21. Validate user input
21. Validate user input
python
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a valid number")
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a valid number")
22. Read a configuration file
22. Read a configuration file
python
try:
with open("config.json", "r") as file:
config = file.read()
except FileNotFoundError:
print("Configuration file not found. Using defaults.")
try:
with open("config.json", "r") as file:
config = file.read()
except FileNotFoundError:
print("Configuration file not found. Using defaults.")
23. API request with error handling
23. API request with error handling
python
import requests
try:
response = requests.get("https://api.example.com/data")
data = response.json()
except requests.exceptions.RequestException as e:
print("Request failed:", e)
import requests
try:
response = requests.get("https://api.example.com/data")
data = response.json()
except requests.exceptions.RequestException as e:
print("Request failed:", e)
24. Division with zero check
24. Division with zero check
python
try:
num = 10
denom = 0
result = num / denom
except ZeroDivisionError:
print("Cannot divide by zero")
try:
num = 10
denom = 0
result = num / denom
except ZeroDivisionError:
print("Cannot divide by zero")
25. File upload size limit
25. File upload size limit
python
def upload_file(size_mb):
if size_mb > 100:
raise OverflowError("File size exceeds 100MB limit")
try:
upload_file(120)
except OverflowError as e:
print("Upload failed:", e)
def upload_file(size_mb):
if size_mb > 100:
raise OverflowError("File size exceeds 100MB limit")
try:
upload_file(120)
except OverflowError as e:
print("Upload failed:", e)
26. Dictionary key lookup
26. Dictionary key lookup
python
products = {"apple": 10, "banana": 5}
try:
print("Price:", products["orange"])
except KeyError:
print("Product not found")
products = {"apple": 10, "banana": 5}
try:
print("Price:", products["orange"])
except KeyError:
print("Product not found")
27. Custom exception example
27. Custom exception example
python
class NegativeNumberError(Exception):
pass
number = -5
try:
if number < 0:
raise NegativeNumberError("Negative number not allowed")
except NegativeNumberError as e:
print("Error:", e)
class NegativeNumberError(Exception):
pass
number = -5
try:
if number < 0:
raise NegativeNumberError("Negative number not allowed")
except NegativeNumberError as e:
print("Error:", e)
28. Logging an exception
28. Logging an exception
python
import logging
logging.basicConfig(filename="app.log", level=logging.ERROR)
try:
result = 5 / 0
except ZeroDivisionError as e:
logging.error("Division error occurred", exc_info=True)
import logging
logging.basicConfig(filename="app.log", level=logging.ERROR)
try:
result = 5 / 0
except ZeroDivisionError as e:
logging.error("Division error occurred", exc_info=True)
What’s Next?
Now that you know how to handle errors, it's time to learn about classes and objects. These are important concepts in Python that will help you organize and manage your code better. In the next section, we’ll go over examples of how to use classes and objects in Python.