Table of Contents
This guide covers exception handling - exception handling in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
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 app 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.
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 TipsMake in the introduction to Exception.
For example:
# import module sys để gọi ra các ngoại lệimport sysrandomList = ['a', 0, 2]for nhap in randomList:try:print("Phần tử:", nhap)r = 1/int(nhap)breakexcept: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ử: aCó ngoại lệ xảy ra.Có ngoại lệ xảy ra.Nhập phần tử tiếp theoPhần tử: 0Có ngoại lệ xảy ra.Có ngoại lệ xảy ra.Nhập phần tử tiếp theoPhần tử: 2Kế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
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 tryexcept exceptionName:# khối code lệnh except
Parameters:
- 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 tryexcept ValueError:# code xử lý ValueErrorexcept 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 tryexcept (TypeError, ZeroDivisionError):# code xử lý nhiều ngoại lệ# TypeError, ZeroDivisionError
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 Exceptionprint '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 KeyboardInterruptTraceback (most recent call last):File " ", line 1, inFile " ", line 1, inraise KeyboardInterruptKeyboardInterrupt>>> raise MemoryError("Đây là một tham số.")Traceback (most recent call last):File " ", line 1, inFile " ", line 1, inraise 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: -2Số bạn vừa nhập không phải số nguyên dương.
Try. Finally Is another way to write Try In Python.
To finish, 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 To finish, 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ệpfinally: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.")
To finish, 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ố: 5Kết quả là: 3.0Bạ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ố: 0Bạn đã nhập số không thể thực hiện phép tính.
So TipsMake 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 TipsMake!
Previous post: Error and Exception in Python
Next lesson: Object-oriented programming in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.