Exception handling - Exception Handling in Python

In this article, Quantum will work with you to learn how to handle exceptions in Python using Try, Except and Finally. This will motivate you to write more neat, readable and efficient code.

In this article, Quantum will work with you to learn how to handle exceptions in Python using Try, Except and Finally. This will motivate you to write neat, readable and effective code in Python.

main content

  1. Exception in Python
  2. Handling exceptions in Python
  3. Specific handling of an exception
  4. Build an Exception
  5. Try . Finally

Exception in Python

Exception is an error that occurs during the execution of a program. When it happens, Python creates an exception to handle that problem to prevent your application or server from crashing.

Exceptions can be any unusual condition in the program that breaks the program execution flow. Whenever an exception occurs, the program will stop executing, switch to the calling process, and print an error until it is processed.

Exception handling - Exception Handling in Python Picture 1Exception handling - Exception Handling in Python Picture 1

Handling exceptions in Python

In Python, exceptions can be handled with the try . except statement block .

The try body will include code that can generate an exception, if an exception is created, all statements in the block will be ignored.

On the other hand, the except body is called by exception handler, because it is used to catch errors. The except block will execute when an error is generated, otherwise it will be ignored. You can use the available exception in the Python Standard Library mentioned by Quantrimang in the introduction to Exception.

For example:

 # import module sys để gọi ra các ngoại lệ 
import sys

randomList = ['a', 0, 2]

for nhap in randomList:
try:
print("Phần tử:", nhap)
r = 1/int(nhap)
break
except:
print("Có ngoại lệ ",sys.exc_info()[0]," xảy ra.")
print("Nhập phần tử tiếp theo")
print()
print("Kết quả với phần tử",nhap,"là:",r)

The results for the screen are as follows:

 Phần tử: a 
Có ngoại lệ xảy ra. Có ngoại lệ xảy ra.
Nhập phần tử tiếp theo

Phần tử: 0
Có ngoại lệ xảy ra. Có ngoại lệ xảy ra.
Nhập phần tử tiếp theo

Phần tử: 2
Kết quả với phần tử 2 là: 0.5

In this example, the program will execute until the correct number is entered as an integer.

If no exception occurs, the except block will be ignored and the program follows the normal flow, but if there are any exceptions it will be blocked by the except.

The program also prints the name of the exception with the ex_info () function inside the sys module , the result returned is the value 'a' causing ValueError and 0 causing ZeroDivisionError

Specific handling of an exception

In the above example, there is no specific exception mentioned in the except clause, so when the program has an exception (even if any exceptions), they are processed in one way.

In addition to that, we can specify specific exceptions for the except command block .

The syntax is as follows:

 try: 
# khối code lệnh try
except exceptionName:
# khối code lệnh except

Parameters:

  1. The exceptionName is the name of the exception you think is likely to occur.

A try clause can have multiple except clauses to handle them differently.

If the block in a try has an error, the program will find the below except , if except is satisfied, it will execute the code in that except block.

 try : 
# khối code lệnh try

except ValueError:
# code xử lý ValueError

except RuntimeError:
# code xử lý RuntimeError

You can also catch multiple exceptions on an exception declaration by placing exceptions separated by a comma ','

 try : 
# khối code lệnh try

except (TypeError, ZeroDivisionError):
# code xử lý nhiều ngoại lệ
# TypeError, ZeroDivisionError

Build an Exception

Building an exception using raise is another way to handle exceptions in Python. In this case, you can create your own exception - that's the exception raised when the problem is outside the range of the expected error.

For example:

 try: 
x = input('Nhập một số trong khoảng 1-10: ')
if x10:
raise Exception
print 'Bạn vừa nhập một số hợp lệ :D'

except:
print 'Số bạn vừa nhập nằm ngoài khoảng cho phép mất rồi!'

In this example, if you enter a number outside the allowed ranges, the print commands in the except blocks will be executed.

Traceback module

The traceback module is another way to handle exception in Python. It is basically used to print the trace of the program after an exception occurs.

Traceback includes error messages, line numbers that cause errors and call stack functions that cause an error.

 >>> raise KeyboardInterrupt 
Traceback (most recent call last):
File " ", line 1, in File " ", line 1, in
raise KeyboardInterrupt
KeyboardInterrupt

>>> raise MemoryError("Đây là một tham số.")
Traceback (most recent call last):
File " ", line 1, in File " ", line 1, in
raise MemoryError("Đây là một tham số.")
MemoryError: Đây là một tham số.

>>> try:
. a = int(input("Nhập một số nguyên dương: "))
. if a <= 0:
. raise ValueError("Số bạn vừa nhập không phải số nguyên dương.")
. except ValueError as ve:
. print(ve)
.
Nhập một số nguyên dương: -2
Số bạn vừa nhập không phải số nguyên dương.

Try . Finally

Try . finally is another way to write try in Python.

Finally is also called a clean-up / termination clause because it always runs regardless of any errors in the try block.

Often the statements in the finally are used to perform the release of resources.

Examples of file operations to clearly illustrate finally:

After you've done the file manipulation in Python, you need to close it. Close the file to ensure the opening and closing regulations for the program.

 try: 
f = open("test.txt",encoding = 'utf-8')
# thực hiện các thao tác với tệp
finally:
f.close()

In this way, we can be assured that the file is closed properly even when an exception is raised that makes the program stop unexpectedly.

Another example is an exception:

 mauso = input("Bạn hãy nhập giá trị mẫu số: ") 
try:
ketqua = 15/int(mauso)
print("Kết quả là:",ketqua)
finally:
print("Bạn đã nhập số không thể thực hiện phép tính.")

Finally always runs regardless of whether an error has occurred or not.

When you enter input as 5, the program returns the result:

 Bạn hãy nhập giá trị mẫu số: 5 
Kết quả là: 3.0
Bạn đã nhập số không thể thực hiện phép tính.

And when the input is 0, the result displays:

 Bạn hãy nhập giá trị mẫu số: 0 
Bạn đã nhập số không thể thực hiện phép tính.

So Quantrimang showed you the basics of handling exceptions in Python. Hope that the article will be useful for you.

You can immediately check the knowledge you have just learned through our Python test on exception handling.

And remember to revise regularly with Python and Quantrimang!

Previous post: Error and Exception in Python

Next lesson: Object-oriented programming in Python

4 ★ | 1 Vote