SoFunction
Updated on 2024-11-16

Examples of Python exception handling operations in detail

This article example describes Python exception handling operations. Shared for your reference, as follows:

I. Introduction of exception handling

>>>whileTrue:
try:
x = int(input("Please enter a number: "))
break
exceptValueError:
print("Oops! That was no valid number. Try again ")
Please enter a number: y
Oops!That was no valid  again
Please enter a number:1.3
Oops!That was no valid  again
Please enter a number:5

II. How the try statement works

1. Execute the try clause (the statement between the keyword try and the keyword except)

2. If no exception occurs, the except clause is ignored and the try clause ends after execution.

3. If an exception occurs during execution of the try clause, the remainder of the try clause is ignored. If the type of the exception matches the name of the exception, then the corresponding except clause is executed. Finally, the code following the try statement is executed.

4. If an exception is not matched with any except, then the exception will be passed to the upper level of the try.

5. A try statement may contain multiple except clauses to handle different specific exceptions. At most, only one branch will be executed.

6. The handler will only handle exceptions in the corresponding try clause.

7, an except clause can handle multiple exceptions at the same time, these exceptions will be placed in parentheses to become a tuple, for example.

except (RuntimeError, TypeError, NameError):
    pass

8. The last except clause allows you to ignore the name of the exception, which will be used as a wildcard. You can use this method to print an error message and then throw the exception again.

>>>import os
>>>try:
f = open('')
s = ()
i = int(())
exceptOSErroras err:
print("OS error: {0}".format(err))
exceptValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
OS error:[Errno2]No such file or directory:''

III. The else clause

The try except statement also has an optional else clause which, if used, must be placed after all except clauses. This clause will be executed when no exception occurs in the try clause.

>>>try:
f = open('','r')
exceptIOError:
print('cannot open')
except:
print('other ERR')
else:
print('file close')
()
cannot open

It's better to use the else clause than to put all the statements inside the try clause, so that you can avoid unexpected exceptions that are not caught by except.

IV. Functions in the exception handling try

Exception handling doesn't just handle exceptions that occur directly in the try clause, but also exceptions thrown by functions called in the clause (or even indirectly).

>>>def this_fails():
x =1/0
>>>try:
this_fails()
exceptZeroDivisionErroras err:
print('Handling run-time error:', err)
Handling run-time error: division by zero

For more Python related content, readers can check out this site's topic:Python introductory and advanced classic tutorials》、《Summary of Python string manipulation techniques》、《Python list (list) manipulation techniques summarized》、《Summary of Python coding manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tipsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.