Error Handling in Python
In this article, we will explain error handling in Python.
YouTube Video
Error Handling in Python
Error handling in Python is mainly done using the keywords try
, except
, else
, and finally
. Using these constructs enables you to respond appropriately when an error occurs in your program. Below, we will explain how to use each of them.
try
Block
Within the try
block, you write the code you want to execute. If an error occurs within this block, program execution immediately transitions to the except
block.
1try:
2 # Code that may raise an error (division by zero, for example)
3 #number = int(input("Enter a number: "))
4 number = int("abc")
5 result = 10 / number
6 print("Result:", result)
7except ValueError as e:
8 # Handle invalid input (e.g. non-numeric input)
9 print("Invalid input. Please enter a whole number.")
10 print(f"Value error: {e}")
11except ZeroDivisionError as e:
12 # Handle division by zero error
13 print("Cannot divide by zero!")
14 print(f"Zero division error: {e}")
- This code is an example of detecting errors in a
try
block and appropriately handling them by catching eitherValueError
orZeroDivisionError
.
except
Block
In the except
block, you write the code that will execute when a specific exception (error) occurs. You can also catch specific exceptions depending on the type of exception that occurs.
1try:
2 #number = int(input("Enter a number: "))
3 number = 0
4 result = 10 / number
5 print("Result:", result)
6except ZeroDivisionError as e:
7 print("Cannot divide by zero!")
8 print(f"Zero division error: {e}")
9except ValueError as e:
10 print("Input was not a valid integer.")
11 print(f"Value error: {e}")
- This code is an example of executing different handling for each type of exception in the
except
block when an error occurs in thetry
block.
Handling multiple exceptions together
Specify a tuple when multiple exception classes can share the same handling logic.
1try:
2 my_list = [1, 2]
3 result = my_list[3] + 10 / 0
4except (IndexError, ZeroDivisionError) as e:
5 print(f"Exception occurred: {e}")
- This code is an example of catching both
IndexError
andZeroDivisionError
together and handling the exceptions in the same way.
Catching exceptions unconditionally
Omit the argument for except
if you want to handle all types of exceptions in one block.
1try:
2 # This code might cause some exception
3 result = "10" + 5 # TypeError
4except Exception as e:
5 print("Unexpected error")
- However, handling specific exceptions rather than unconditionally catching all exceptions is more helpful for finding bugs and debugging. Whenever possible, explicitly handling only anticipated exceptions such as
ValueError
orTypeError
will increase the robustness of your code.
else
block
else
block is only executed if no errors occur within the try
block.
1try:
2 #number = int(input("Enter a number: "))
3 number = 5
4 result = 10 / number
5except ZeroDivisionError as e:
6 print("Cannot divide by zero!")
7 print(f"Zero division error: {e}")
8except ValueError as e:
9 print("Input was not a valid integer.")
10 print(f"Value error: {e}")
11else:
12 # This block will execute only if no exceptions were raised
13 print("Result:", result)
- This code is an example where the
else
block is executed only if no error occurs in thetry
block.
finally
block
The finally
block is used to write code that will always execute at the end, regardless of whether an error occurred in the try
block. It is useful for releasing resources or performing cleanup tasks.
1try:
2 #number = int(input("Enter a number: "))
3 number = int("abc")
4 result = 10 / number
5except ZeroDivisionError as e:
6 print("Cannot divide by zero!")
7 print(f"Zero division error: {e}")
8except ValueError as e:
9 print("Input was not a valid integer.")
10 print(f"Value error: {e}")
11else:
12 # This block will execute only if no exceptions were raised
13 print("Result:", result)
14finally:
15 # This block will always execute, regardless of whether an exception was raised
16 print("Execution completed.")
- This code is an example demonstrating that the
finally
block is executed regardless of whether an exception occurs or not.
The raise
keyword
It is also possible to raise an exception using the raise
keyword when certain conditions in existing code are not met.
1def divide(a, b):
2 if b == 0:
3 raise ValueError("Cannot divide by zero.")
4 return a / b
5
6try:
7 result = divide(10, 0)
8except ValueError as e:
9 print(f"Error: {e}")
- This code is an example of explicitly raising an exception using the
raise
keyword when a condition is not met.
Conclusion
By handling errors in this way, you can prevent program crashes, display appropriate messages to the user, and continue with subsequent program processing.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.