Python Exception Handling A-Z Guide for Programmers and Testers

Just ask from any programmer or an automation tester, he’ll tell you how critical is exception handling for creating robust and stable applications. That’s why, after our last post on file handling, we put our thoughts to deliver a Python exception handling tutorial.

You’ll all accept that each one of us may leave errors while writing programmable code. After all, we are humans. Sometimes we make a syntactical mistake or provide a wrong input to the program.

Also, a program may fail if it needs a network resource which is not available. Even it may face out of memory and similar errors.

Some of these errors may cause the program to terminate abruptly. Since none of us want a program to behave nasty, so we make arrangements to handle such situations.

With the help of Python exception handling, we can manage the above issues and avoid intermittent failures of our code. The most common way to do it is by creating a python try-except block.

Now, let’s begin exploring the A-Z guide of Python exception handling. Here are some quick bullet points to walk you through the entire tutorial.

Python Exception Handling Tutorial for Beginners.

First of all, we have to understand the difference between an error and the exception. Consequently, we’ll teach you the essentials of Python exception handling.

The difference between an error and the exception.

What is Error?

The error is something that goes wrong in the program, e.g. like a syntactical error.

It occurs at compile time. Let’s see an example.

 

What is Exception?

The errors also occur at runtime, and we know them as exceptions. An exception is an event which occurs during the execution of a program and disrupts the normal flow of the program’s instructions.

In general, when a Python script encounters an error situation that it can’t cope with, it raises an exception.

When a Python script raises an exception, it creates an exception object. Usually, the script handles the exception immediately. If it doesn’t do so, then the program will terminate and print a traceback to the error along with its whereabouts.

 

How to handle an Exception?

Like many languages, in Python, a try statement is available for exception handling.

In every try block, there is a piece of code which can raise an exception. And the code that handles the exception, we place in the except clause.

Following is the syntax of a <Python try except else> block.

 

Checklist to handle an exception in Python.

Here is a checklist for using the Python try statement effectively.

  • A single try statement can have multiple except statements depending on the requirement. In this case, a try block contains statements that can throw different types of exceptions.
  • We can also add a generic except clause which can handle all possible types of exceptions.
  • We can even include an else clause after the except clause. The code in the else block will execute if the code in the try block doesn’t raise any exception.

 

Python exception handling # example-1.

Let’s take a sample code to understand the use of <Python try-except>.

The above code produces the following output.

 

Python exception handling # example-2.

Let’s take another example in which we are trying to open a file in read mode. Then, we’ll perform <write> operation on it. Upon execution, it’ll throw the following exception.

The above code produces the following output.

 

How to define except Clause with No Exceptions?

Defining except clause with no exceptions enables it to handle all types of exceptions. However, neither it’s a good programming practice nor does anyone recommend it.

It is because that such a Python try-except block can handle all types of exceptions. But it’ll not help the programmer to find which type of exception caused the issue.

If you still want to use it, then refer the following code.

Python exception handling # example-3.

 

How to use except Clause with Multiple Exceptions?

We can define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under the except clause.

In short, when we define except clause in this way, we expect the same piece of code to throw different exceptions. Also, we want to take the same action in each case.

Please refer the below example.

Python exception handling # example-4.

 

How to use <try-finally> clause in Python?

With try block, we also have the option to define the <finally> block. This clause allows defining statements that we want to execute, no matters whether the try block has raised an exception or not.

This feature usually comes in the picture while releasing external resources.

Here is the coding snippet for help.

 

Python exception handling # example-5.

One very important point is that we can either define a <except> or a <finally> clause with every try block. You can’t club these together. Also, you shouldn’t use the <else> clause along with a <finally> clause.

Let’s take an example to get more clarity.

If the exception doesn’t occur, then you’ll see the following output.

 

Python exception handling # example-6.

Suppose we open the file in read mode and then try to perform a write operation on it. In such a situation, below code will help to handle the exception.

 

In this case, the interpreter will raise an exception and the following output will get displayed.

When some code causes an exception in a try block, the execution immediately passes to the <finally> block. After all the statements in the <finally> block get executed, the exception resumes to the <except> block for execution. But there must present a next higher layer of the <try-except> statement.

 

How to raise an exception and provide arguments?

We can forcefully raise an exception using the raise keyword. We can also optionally pass values to the exception and specify why this exception should occur. Here is the syntax for calling the <raise> method.

where,

  • The exception is the name of the exception.
  • <args> is optional and represents the value of the exception argument.
  • The final argument, traceback, is also optional and if present, is the traceback object used for the exception.

Let’s take an example to clarify this.

Python exception handling # example-7.

 

User-Defined Exceptions.

How to define a custom exception in Python?

We can add user-defined exceptions by creating a new class in Python. The trick here is to derive the custom exception class from the base exception class. Most of the built-in exceptions use the same technique to enforce their exceptions.

Create an exception class in Python.

In the above code snippet, you can see that we have created a user-defined exception class, the <UserDefinedError>. It is using the base Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does i.e. by calling the <raise> statement with an optional error message.

Let’s take an example.

Python exception handling # example-8.

In this example, we will show how does an user-defined exception raise and catch errors in a program. In this sample, we will ask the user to enter an alphabet again and again until he enters the stored alphabet only.

For help, the program provides a hint to the user so that he can figure out the correct alphabet. Also, he can check whether his guess is greater or less than the stored alphabet.

Example-8# Run with multiple tests data.

Let’s test this program by supplying different inputs.

Thus you can see that we have defined a base class called Error here in this program. The two exceptions (<InputTooSmallError> and <InputTooLargeError>) that are raised by our program are derived from this class. It’s the standard way to define user-defined exceptions in Python programming.

List of Python Built-in Exceptions.

Exception Cause of Error
<AirthmeticError> For errors in numeric calculation.
<AssertionError> If the assert statement fails.
<AttributeError> When an attribute assignment or the reference fails.
<EOFError> If there is no input or the file pointer is at EOF.
<Exception> It is the base class for all exceptions.
<EnvironmentError> For errors that occur outside the Python environment.
<FloatingPointError> When floating point operation fails.
<GeneratorExit> If a generator’s <close()> method gets called.
<ImportError> When the imported module is not available.
<IOError> If an input/output operation fails.
<IndexError> When the index of a sequence is out of range.
<KeyError> If the specified key is not available in the dictionary.
<KeyboardInterrupt> When the user hits interrupt key (Ctrl+c or delete).
<MemoryError> If an operation runs out of memory.
<NameError> When a variable is not available in local or global scope.
<NotImplementedError> If an abstract method isn’t available.
<OSError> When a system operation fails.
<OverflowError> If the result of an arithmetic operation exceeds the range.
<ReferenceError> When a weak reference proxy accesses a garbage collected reference.
<RuntimeError> If the generated error doesn’t fall under any category.
<StandardError> It is a base class for all built-in exceptions except <StopIteration> and <SystemExit>.
<StopIteration> The <next()> function has no further item to be returned.
<SyntaxError> For errors in Python syntax.
<IndentationError> When indentation is not proper.
<TabError> For inconsistent tabs and spaces.
<SystemError> When interpreter detects an internal error.
<SystemExit> The <sys.exit()> function raises it.
<TypeError> When a function is using an object of the incorrect type.
<UnboundLocalError> If the code using an unassigned reference gets executed.
<UnicodeError> For a Unicode encoding or decoding error.
<ValueError> When a function receives invalid values.
<ZeroDivisionError> If the second operand of division or modulo operation is zero.

Final Word.

We most of the time try to pick a topic that can help in your work. Also, we intend to teach you skills that matter the most in your job profile. That’s why we came up with this blog post on Python exception handling.

It would be great to hear from you if this post helped you in learning Python. So do let us know about your experience.

Also, you can submit a request for any topic of your choice. We’ll include it in our plan and add to the priority list.

If you liked the post, then please don’t miss to share it with friends and on social media.

Teaching is the best asset that a person should share without any cost.

Keep Learning,

TechBeamers.

2 Comments

  1. Srinivas Kotaru Reply

Leave a Reply


*