Understanding Exception Handling in Python
What is an Exception?
Exceptions are errors that occur during the execution of your code. Before running a script, Python checks for syntax errors, but even if the syntax is correct, runtime errors, called exceptions, can still occur. In this chapter, we’ll explore how exceptions work in Python and how you can handle them using try
, except
, else
, and finally
blocks. We’ll also cover handling multiple exceptions, raising your own exceptions, and using the assert
statement for validation. By the end of this chapter, you’ll know how to handle errors gracefully in your programs and ensure they run smoothly even when something goes wrong.
For example, in the code below, there are no syntax errors. However, during execution, the 2nd line “c = a /
b” will cause an exception because the value of the variable “b” is zero and dividing by zero is not allowed.
a, b = 10, 0
c = a / b
#Output:
Traceback (most recent call last):
File "except.py", line 2, in <module>
c = a / b
ZeroDivisionError: division by zero
Some other common exceptions are: ValueError, TypeError, NameError, SyntaxError, FileNotFound Error etc
ValueError : This exception is raised when a function gets a valid data type but an invalid value. For example, trying to convert a non-numeric string into an integer as show in below code:
a = "hi"
b = int(a)
#Output:
Traceback (most recent call last):
File "except.py", line 2, in <module>
b = int(a)
ValueError: invalid literal for int() with base 10: 'hi'
TypeError: Raised when you perform an operation on a data type that doesn’t support it. For example, trying to add a string and an integer together as shown below:
a = "hello" + 5
#Output :
Traceback (most recent call last):
File "except.py", line 1, in <module>
a = "hello" + 5
TypeError: can only concatenate str (not "int") to str
NameError: Raised when a variable or function name is not found in the local or global namespace. For example, the following simple code uses a variable that hasn’t been defined and will raise a NameError.
a = hello
#Output:
Traceback (most recent call last):
File "except.py", line 1, in <module>
a = hello
NameError: name 'hello' is not defined
FileNotFoundError: Raised when attempting to open a file that does not exist. For example, the following code uses the open
function to open the file abcd.txt
in read-only mode and will raise a FileNotFoundError if the file does not exist in the same folder as the script.
file_id = open ("abcd.txt" , r)
#Output:
Traceback (most recent call last):
File "except.py", line 1, in <module>
fid = open("abcd.txt", 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'abcd.txt'
What is Exception Handling?
Exception handling is the technique of catching errors to prevent the unexpected termination of a script. If you suspect a part of your code may raise an error, you can use the try-except block to handle that exception.
For example, to handle the FileNotFoundError
in the code above:
try:
fid = open("abcd.txt", 'r')
except FileNotFoundError:
print("File is not present, skipping the reading process...")
else:
print(fid.read())
fid.close()
In this code:
- The
try
block contains the code that might raise an exception. - If a
FileNotFoundError
occurs, theexcept
block will be executed. - If no error occurs, the
else
block is executed.
Handling Multiple Exceptions
You can catch multiple exceptions by using either a tuple of exceptions or multiple except
clauses.
Using a Tuple of Exceptions:
try:
fid = open("abcd.txt", 'r')
fid.write("hello world")
except (FileNotFoundError, IOError):
print("Error in opening file or writing ...")
else:
fid.close()
Using Multiple except
Clauses:
try:
fid = open("abcd.txt", 'r')
fid.write("hello world")
except FileNotFoundError:
print("Error in opening file")
except IOError:
print("File opened successfully, but couldn't write")
else:
fid.close()
Using “finally
” in Exception Handling :
The “finally"
block is used to execute code regardless of whether an exception is raised. It is typically used to release resources like closing files or network connections. In the following example, the “finally
“ block will always run, whether or not an exception is raised.
fid = open("abcd.txt", 'r')
try:
fid.write("hello world")
except IOError:
print("Write operation: Failed")
else:
print("Write operation: Successful")
finally:
print("Inside finally...")
fid.close()
User-Defined Exceptions
You can create custom exceptions by defining a new class that inherits from the built-in “Exception
” class. You can use this custom exception with the “raise
” keyword to trigger the exception manually. For example, the following code will print a range of numbers if the user input is a number greater than 0 , but will exit the code raising the MyInputError defined by the user if the user’s input is less than 0.
Raising a Custom Exception:
class MyInputError(Exception):
pass
a = int(input("Enter a number: "))
try:
if a <= 0:
raise MyInputError()
except MyInputError:
print("Enter a number greater than 0")
else:
for tmp in range(a):
print(tmp)
Exception Arguments
When raising an exception, you can pass arguments to it, which can be used later in the except
block or displayed if not caught.
a = int(input("Enter a number: "))
class MyInputError(Exception):
pass
try:
if a < 0:
raise MyInputError("Input is less than 0")
if a < 5:
raise MyInputError("Input is less than 5")
except MyInputError as tmp:
print(tmp)
else:
for tmp in range(a):
print(tmp)
#Output :
Enter a number: 3
Input is less than 5
Python’s “assert
” Statement
The “assert"
statement is used to verify that a condition holds true. If the condition is false, an AssertionError
is raised.
a = int(input("Enter a number: "))
assert a > 0, "Wrong Input"
for tmp in range(a):
print(tmp)
#Output (If the input is less than or equal to zero)
Traceback (most recent call last):
File "except.py", line 2, in <module>
assert a > 0, "Wrong Input"
AssertionError: Wrong Input
We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.
About The Author:
Sajith Achipra has been a trainer and testing consultant at Zframez Technologies since 2009. With 15+ years of experience, he specializes in networking, Python, development, and testing. He conducts online courses to help students and professionals enhance their skills. You can reach him on WhatsApp at +91 8884 884 844 for your training and testing requirements.