Chapter 12: Exception Handling in Python -Techniques and Examples

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.

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:

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:

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.

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.

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:

In this code:

  • The try block contains the code that might raise an exception.
  • If a FileNotFoundError occurs, the except 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:

Using Multiple except Clauses:

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.

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 “raisekeyword 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:

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.

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.



We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.

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.