Python Exception Handling - Try, Except and Finally

2018-05-03

Python Exception Handling - Try, Except and Finally

Python Exception Handling - Try, Except and Finally

In this article, you'll learn how to handle exceptions in your Python program using try, except and finally statements. This will motivate you to write clean, readable and efficient code in Python.

Table of Contents

What are exceptions in Python?

Catching Exceptions in Python

Catching Specific Exceptions in Python

Raising Exceptions

try...finally

What are exceptions in Python?

Python has many built-in exceptionswhich forces your program to output an error when something in it goes wrong.

When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash.

For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A.

If never handled, an error message is spit out and our program come to a sudden, unexpected halt.

Catching Exceptions in Python

In Python, exceptions can be handled using a try statement.

A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause.

It is up to us, what operations we perform once we have caught the exception. Here is a simple example.


# import module sys to get the type of exception

import sys

randomList = ['a', 0, 2]

for entry in randomList:

    try:

        print("The entry is", entry)

        r = 1/int(entry)

        break

    except:

        print("Oops!",sys.exc_info()[0],"occured.")

        print("Next entry.")

        print()

print("The reciprocal of",entry,"is",r)

Output

The entry is a

Oops! <class 'ValueError'> occured.

Next entry.

The entry is 0

Oops!  <class 'ZeroDivisionError'> occured.

Next entry.

The entry is 2

The reciprocal of 2 is 0.5

In this program, we loop until the user enters an integer that has a valid reciprocal. The portion that can cause exception is placed inside try block.

If no exception occurs, except block is skipped and normal flow continues. But if any exception occurs, it is caught by the except block.

Here, we print the name of the exception using ex_info() function inside sys module and ask the user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes ZeroDivisionError.

Catching Specific Exceptions in Python

In the above example, we did not mention any exception in the except clause.

This is not a good programming practice as it will catch all exceptions and handle every case in the same way. We can specify which exceptions an except clause will catch.

A try clause can have any number of except clause to handle them differently but only one will be executed in case an exception occurs.

We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo code.

try: 

         # do something  

         pass

except ValueError: 

         # handle ValueError exception 

         pass

except (TypeError, ZeroDivisionError): 

         # handle multiple exceptions 

         # TypeError and ZeroDivisionError 

         pass

except: 

         # handle all other exceptions 

         pass

Raising Exceptions

In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.

We can also optionally pass in value to the exception to clarify why that exception was raised.

>>> raise KeyboardInterrupt

Traceback (most recent call last):

...

KeyboardInterrupt

>>> raise MemoryError("This is an argument")

Traceback (most recent call last):

...

MemoryError: This is an argument

>>> try:

...            a = int(input("Enter a positive integer: "))

...            if a <= 0:

...                     raise ValueError("That is not a positive number!")

...     except ValueError as ve:

...                 print(ve)

...    

Enter a positive integer: -2

That is not a positive number!

try...finally

The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources.

For example, we may be connected to a remote data center through the network or working with a file or working with a Graphical User Interface (GUI).

In all these circumstances, we must clean up the resource once used, whether it was successful or not. These actions (closing a file, GUI or disconnecting from network) are performed in the finally clause to guarantee execution.

Here is an example of file operations to illustrate this.

try:  

     f = open("test.txt",encoding = 'utf-8') 

     # perform file operations

finally:  

     f.close()

This type of construct makes sure the file is closed even if an exception occurs.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,900评论 0 23
  • 她是机器人--她是机器人--- 一个可爱的智能机器人, 一个拥有肉体和流动着血液的机器人, 一个会思维会想象会计算...
    张译刈阅读 658评论 0 2
  • 一年级入学三天了,儿子慢慢的在适应,也有委屈,和退缩。 儿子上的是全日...
    做自己命运的主宰阅读 343评论 1 1
  • ――心灵自由小组第13篇―― 去西湖东坡纪念馆时,明明记得苏学士两行诗: 静若了群动,空必纳万境。 读过后念念不忘...
    Sophie_L阅读 130评论 0 0