Python Exception Handling and Tricks By albro

Python Exception Handling and Tricks

Some program errors that we have written occur during execution and according to the conditions. If an inappropriate input is entered by the user or the program cannot open a file, we will encounter a type of error called an exception. In this post, I'll talk about Exception Handling in Python and at the end we will be able to handle all types of exceptions in Python.

As you know, we have various errors in programming. Some are written errors and some are logical errors. Another type of error in programming is the errors that occur during the execution of the program and cause it to stop. Such errors are also called exceptions.

Suppose in your application you asked the user to enter numerical settings. The user uses letters instead of entering numbers. If you want to perform processing on this input value (addition, subtraction and division, etc.) you will definitely encounter an error.

It's better to always try to avoid errors that may occur in programming. This will be done by error management (exception handling). In the following, after examining error management in Python, I'll discuss how to handle exceptions in Python.

Error in Python

In general, Python has two methods for handling unexpected errors in programs. These two solutions are:

  • Exception Handling: In this method, we will manage parts of the program that may cause errors, and in case of errors, we will do alternative work.
  • Test functions (Assertion): Using this method, we can check the input and output of a function or operation. If there was a problem with the expected input and output, we make decisions to continue the program.

I'll discuss the first in this post. The second one is mostly used when the output of a task is predictable. That is, we know that the output of the function to the second power is always equal to the input to the power of two! But in the parts where the error may occur due to user mistake or system problems, better performance can be achieved by using exception handling in Python.

Exceptions in Python

Every error that occurs during the execution of Python code contains a name and is of a specific type. Exceptions are also a type of error. As a result, they all have names that can help us better manage errors.

Suppose I have a text string that I want to convert to a number. For this, I use the int() function and give it the string as input. If there are only numbers in the string, the operation is successful and my output will be an integer.

num = "2568"
print( int(num) )
# output: 2568

But if there are letters in addition to numbers in our string, I'll encounter an error.

num = "25albro68"
print( int(num) )

At the beginning of the last line of the error that occurred, the type of error (exception) is specified. A ValueError occurs when the function input is incorrect. Here I gave incorrect input to the int() function which caused this error.

Traceback (most recent call last):
  File ".\run.py", line 2, in 
    print( int(num) )
ValueError: invalid literal for int() with base 10: '25albro68'

There are various errors and exceptions in the Python language, some of the most frequent exceptions are:

  • Exception: A family of exception types
  • ArithmeticError: Error class for numerical calculations
  • ZeroDivisionError: Specific error of dividing a number by zero
  • TypeError: Function input of object type is not acceptable
  • ValueError: The input argument value of the function is wrong

Exception handling in Python

To better understand exception handling in Python, consider a problem statement.

Suppose I want to take an input from the user and convert it to a number. Then I'll increase it to the power of 2 and print it in the output.

For this, I first get an input from the user with the input() statement. As I receive the input, I convert it to a number and store it in the num variable. Finally, I'll print the second power of the number in the output using the print() statement and the exponent (**) operator.

num = int( input("Please enter the number: ") )
print( num**2 )

If I run the above code and give it the number 5 as input, I'll get the desired result.

Please enter the number: 5
25

If you're not familiar with the input() function and its tricks, you can check out Getting User Input in Python.

But if I accidentally or intentionally enter a letter instead of a number or give it a combination of numbers and letters as input, I'll get a ValueError.

Please enter the number: 7s
Traceback (most recent call last):
  File ".\run.py", line 1, in 
    num = int( input("Please enter the number: ") )
ValueError: invalid literal for int() with base 10: '7s'

I want to avoid this error in Python. Basically I want to make it so that the program doesn't stop when there is a problem with the input. I have two scenarios to continue the program:

  • First scenario: Print an error message to the user and end the program.
  • Second scenario: by printing the error message, get input from the user again and repeat the process.

The try statement for exception handling in Python

With the help of the try statement: we can have a management block. If an error occurs in this block, the program will not stop and we will go to another block (except block).

except statement to manage the error that occurred

We create a block using the except statement. The contents of this block are executed only when an error has occurred in the previous block (i.e. the try block).

This statement is defined in two ways:

  1. general condition
  2. A special case of an exception

The general mode of the except statement

In this case, we write and use the statement as except:. Any error that occurs in the try block, the program will enter this block. It doesn't matter if the error occurred is a ValueError or an error related to opening the file!

special mode of exception handling with except

In this case, we specify the type of error in front of the except keyword and before the colon (:). For example, the following except block is executed if the error occurred in try is of ValueError type.

except ValueError:
    print("Value Error Occurred!")

The finally block in Python error handling

We have another block in exception handling in Python. This block, defined by the finally keyword, is optional and can be used in a try except block.

This block will be executed after the execution of try or except. That is, whether an error occurred or not, the contents of this block will be executed.

An error handling block in Python must contain try and except sections; But the finally block can exist or not as desired.

The example managed program we had will be as follows.

try:
    num = int( input("Please enter the number: ") )
    print( num**2 )
except ValueError:
    print("Please enter a nubmer as input!")

If we want to use the finally block and announce the end of the program, the code can be changed as follows.

try:
    num = int( input("Please enter the number: ") )
    print( num**2 )
except ValueError:
    print("Please enter a nubmer as input!")
finally:
    print("Ended!")

If we run this code and give it the correct input, the output will be something like the following:

Please enter the number: 15
225
Ended!

If we give the same program a wrong input, we will have a result similar to the following:

Please enter the number: 20albro
Please enter a nubmer as input!
Ended!

Each error handling process in Python can only contain a try section and a finally section; But it can have multiple excepts for various types of errors.

For example, in the code above, if we want to prevent other errors that we don't know about, we can use a general except block.

try:
    num = int( input("Please enter the number: ") )
    print( num**2 )
except ValueError:
    print("Please enter only numbers in the entry!")
except:
    print("An unexpected error has occurred!")
finally:
    print("Ended!")

Another example of error handling in Python

Among other things that can cause trouble when programming is working with files. In general, system tasks may cause unexpected errors in our program. For this reason, it is better to use error management techniques when performing operations related to the operating system.

Opening a file may cause unexpected errors. For example:

  • The file is being used by another program and we are not allowed to open it.
  • file does not exist. (wrong path or wrong name and format)

To avoid errors when opening the file, it is better to use try except blocks. In the example below, I first tried to open a file called file.txt and write a text inside it.

try:
    f = open("file.txt")
    f.write("Test from Hive Blockchain")
except:
    print("Something went wrong when writing to the file!")
finally:
    f.close()

tricks

Let's combine the two issues we have discussed so far. That is, first try to open a file and read its first line. Then convert the contents of that line to a number. In this example, we want to predict and manage some possible errors.

The following code would be a desirable result for this task.

try:
    f = open('file.txt')
    s = f.readline()
    i = int( s.strip() )
except OSError:
    print("We have OS error!")
except ValueError:
    print("Could not convert data to an integer!")
except:
    print("Unexpected error!")

I have done the following in the program above:

  • First to fourth line: attempt to perform the desired operation (opening the file, reading it and converting the first line to a number)
  • 5th and 6th line: I handle if an error occurs while opening the file.
  • 7th and 8th line: It is intended to manage the string to number conversion error.
  • 9th and 10th line: I have written this block to handle unwanted error in Python.

Exception generation in Python

When we are writing a function or class in our program, we may need to throw an exception if certain conditions exist. This exception can be one of Python's default exceptions or an exception that we have created ourselves.

However, the raise keyword can be used to generate an error in Python. The general structure of this statement is as follows.

raise [Exception [, args [, traceback]]]

Its first argument is required and the other two are optional.

  • The first argument (Exception): The name or type of exception and error that we want to happen.
  • Second argument (args): This value is considered as the input argument of the called exception.
  • The third parameter (traceback): indicates a stack of errors and events related to the error that occurred.

In the code below, if the value of variable i is greater than 23, we will generate a ValueError.

if i > 23:
    raise ValueError

Summary: Error handling in Python

In this post I talked about error handling in Python. Error management or exception handling in Python is very simple but practical. We can handle unexpected errors by using a block structure.

At first, we try to do something with the try statement. If a problem occurs, we manage it using the except statement or display a suitable message in the output. Finally, with the help of finally, a block can be executed in any condition. That is, whether the try section has been executed successfully or whether we have entered except, the finally block will be executed.

We also defined several except blocks to manage various errors in the program.