Handling Errors in Python, Python Try Except, python with as, Python Try Catch

(Last Updated On: September 12, 2021)

Handling errors in Python (exceptions):

Handling Errors in Python(exceptions)- In this article we are going to be looking at how to handle errors in python. As a beginner you should know about the Python Try Except and also about the python with / as. How does Python respond when an error occurs while running a program? So if you do a division by zero, with l [5] on the fifth element trying to access a list with only four items or if you have a file want to open with open (name, ‘w’) for which your program does not have read permission. In such cases, Python solves like many other modern programming languages raises an exception that informs about the exceptional state. If your program there is no protection against such exceptions, it ends with a unsightly error message. This is exactly what you can avoid if you use your Code Secure try / except.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

try / except

The syntax for try / except is simple:


error-prone code

except aaaError:

Response to a specific error

except bbbError as err:

Reaction to one more error; the

Variable err contains information about the error.

except (cccError, dddError):

Reaction to the errors listed

except (eeeError, fffError) as err:

Reaction to the errors listed; the

Variable err contains information about the error.


Response to all other errors


will be executed if no error has occurred.


is always executed, regardless of whether there is an error occurred or not.

Following try and the code to be secured must be followed by at least an except or follow finally block. All other parts of the try construction are optional. Kick If an error occurs, Python looks for the first except statement that matches the error. except without an error name is considered a default statement that refers to any type of Error applies.

If there is an applicable except block, the code specified there is executed. The error is then considered resolved. The program will follow continued to the try construction.

The code in the else block is executed after the try code, if there no error occurred. In practice, an else block rarely makes sense. The only exception: with the code placed here you can easily determine that the try code was executed without errors.

Code in the finally block is always executed, either following the error-free try code or after an error following the appropriate except code. In contrast to else, finally is used quite often in practice, to carry out cleanup work that is definitely required, for example to close open files or to make database or network connections to end.

In the following example, the code for reading out a file is secured. Possibly a short error message is issued. But what is interesting is the finally Code: Here it is tested whether f is a variable and whether it is not empty: In this case the file is closed. Alternatively, you can also work with/as.


If you formulate the except statement in the formexcept xxxError as var, containsvar is an object of a class that derives from the BaseException class.

When evaluating exception objects, usually only their args of interest. It returns a tuple with all parameters that are required when the Errors were passed. When an exception object is converted to a string is – optionally explicitly through str (e) or implicitly in the print function, then the content of args is automatically converted into a character string.


Errors in functions and methods

For code that is structured by functions or classes, the handling of Errors a little more interesting: When an error occurs, Python first provides determines whether the code is directly secured by try. If this is not the case, the function or quit method.

Now it depends on whether the code was secured by try at that point the function or method call took place. With nested functions and Calling methods, Python works its way down to the lowest execution level of your program. Only if the error protection is also there is missing, the program is aborted with an error message.

For troubleshooting, it is often important to determine how an exception came about. The functions of the traceback module help here. print_exc () indicates which functions and methods were called in which order than the last error occurred.

The following example calls f1 in the try construction. f1 calls again f2 occurs, and division by 0 occurs there. Since neither f2 nor f1 against errors are secured, the try construction is used on the lowest level. The error is found there.

with / as

A basic rule for accessing files and using database and network connections is to make the file or the connection so to close again as quickly as possible in order to avoid these mostly scarce resources to block unnecessarily long. Traditional code to solve this problem is often constructed according to the following pattern:


In the above form, the finally block guarantees that the file will definitely be restored closes – even if an error occurs. Often times the code will also come with except blocks are combined to catch any errors that may occur. With / as offers an alternative approach: With it you can use one or more Open resources and use them in the following block. At the end of the block the resources are automatically closed. The general syntax for with / as

looks like:

with expression1 as var1, expression2 as var2, …: Code that var1, var2 etc. uses The objects contained in var1, var2 etc. are automatically after the with block closed. This assumes that the corresponding classes as so-called Context managers are designed and the corresponding __enter__ and Make __exit_ _ methods available. This requirement is among other things for file objects, so if you want to read a text file and at the same time want to guarantee that the file will also be closed in the event of an error, then you can formulate your code very compactly like this:

with open (‘readme. txt’) as f:

for line in f:

print (line, end = ”)

Throwing exceptions yourself

In functions and methods you have programmed yourself, it is sometimes useful to raise an exception yourself. This way you can be the user of your Inform functions or classes that an error has occurred. Provided you can make use of the exceptions predefined in Python for error reporting find, the code effort is minimal. You simply pass an appropriate one Exception or error object to raise:

def f (x, y):

if x <0 or y <0:

raise ValueError (‘You must specify positive parameters’)

return x * y

If you are not satisfied with the predefined error classes, you have to make the effort and define an appropriate class yourself.

Intercept program interruptions

Python programs running in the terminal can be accessed at any time through (Ctrl) + (C) are canceled. There are two ways to prevent this or initiate at least an orderly retreat when pressing this key combination. One variant uses the try / except presented in this section Construction. The program termination with (Ctrl) + (C) is also considered to be KeyboardInterrupt exception and can therefore be caught:


# Infinite loop

cnt = 0

while 1:

cnt + = 1

print (cnt)

except KeyboardInterrupt:

# Tidying up …

print (‘Ctrl + C was pressed, end of program’)

The other variant uses the signal module to target the SIGINT signal to react, which is sent behind the scenes when a user (Ctrl) + (C) presses. The following example defines the function abort. This function must contain two parameters, even if they are not used here. signal.signal now specifies that the cancel function is called as soon as the Program receives a SIGINT signal.

import signal, sys

def abort (signal, frame):

# Tidying up

print (‘Ctrl + C was pressed, end of program’)

sys. exit (0)

signal. signal (signal. SIGINT, abort)

cnt = 0

# Infinite loop

while 1:

cnt + = 1

print (cnt)

Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

%d bloggers like this: