Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Exception Handling - Exception Handling in Python

Explore Exception Handling - Exception Handling in Python with clear explanations, practical examples, and useful tips.

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 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

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:

  • 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

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 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?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.")

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?: 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 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.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.