This tutorial aims to provide an in-depth exploration of Python's built-in exceptions. Understanding these exceptions will allow you to handle errors effectively in your Python programs.
By the end of this tutorial, you should be able to:
try
, except
, finally
blocksBasic knowledge of Python programming is required. Familiarity with Python's syntax and control flow (such as if
statements and loops) would be beneficial.
Exceptions in Python are events that occur when an error happens during program execution. When a Python script raises an exception, it must either handle the exception immediately or it will terminate and quit.
Python provides several built-in exceptions, such as ZeroDivisionError
, TypeError
, ValueError
, FileNotFoundError
, etc. These exceptions can be triggered when your program encounters an error.
To catch exceptions, use try
and except
blocks. The code that could potentially raise an exception goes in the try
block. The code that handles the exception goes in the except
block.
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Here are some commonly used built-in exceptions:
ZeroDivisionError
: Raised when the second operator in the division is zero.TypeError
: Raised when an operation or function is applied to an object of inappropriate type.ValueError
: Raised when a function receives an argument of the correct type but inappropriate value.FileNotFoundError
: Raised when trying to open a file that does not exist.Let's look at some examples of these exceptions:
ZeroDivisionError
try:
x = 1 / 0 # Division by zero
except ZeroDivisionError:
print("You can't divide by zero!")
# Expected output: You can't divide by zero!
TypeError
try:
'2' + 2 # String and integer addition
except TypeError:
print("You can't add a string to an integer!")
# Expected output: You can't add a string to an integer!
ValueError
try:
int('Python') # Invalid literal for int()
except ValueError:
print("Invalid value for integer conversion!")
# Expected output: Invalid value for integer conversion!
FileNotFoundError
try:
with open('non_existent_file.txt') as f: # File does not exist
print(f.read())
except FileNotFoundError:
print("File not found!")
# Expected output: File not found!
We've covered:
try
and except
blocksNext, you should learn about creating your own custom exceptions and how to raise exceptions manually using the raise
statement. The Python documentation is a great resource for this.
TypeError
when trying to concatenate a string and an integer.ValueError
when trying to convert a string that does not represent an integer.FileNotFoundError
when trying to read a file that does not exist.try:
result = 'Hello' + 1
except TypeError:
print("TypeError caught!")
# Expected output: TypeError caught!
try:
number = int('Hello')
except ValueError:
print("ValueError caught!")
# Expected output: ValueError caught!
try:
with open('non_existent_file.txt') as f:
print(f.read())
except FileNotFoundError:
print("FileNotFoundError caught!")
# Expected output: FileNotFoundError caught!
Remember, practice is key to mastering Python exceptions. Keep experimenting with different scenarios to get a firm grip on the topic!