Python Exception Handling
Python can handle exceptions (Exceptions are error, that are not the normal execution of a program).
Taking care of exceptions is called Exception Handling. Python does that with the try, except and finally blocks.
try
block has code that may raise exceptionsexcept
block handles exceptionsfinally
block code is always executed
Related course: Complete Python Programming Course & Exercises
How to Handle Exceptions in Python?
try, except, finally
is an exception-catching mechanism in Python, which is usually used in combination with try...except
.
If an exception is found, it will be passed to a block in the except
for processing, that is, to execute the statements in the except
. The syntax to handle exceptions is:
try:
pass
except:
pass
finally:
pass
Of course, try...except can also be used in conjunction with finally.
The content of the finally block is run only in the end, but usually does something simple like release a resourceor something.
The finally block is always executed, even if there is an Exception in the previous try and except blocks.
try-except Blocks Example
Here's a simple example of exception handling with a try except
block.
Example example.py
def tryTest():
try:
den = input("input a number:")
x = 1.0/int(den)
print(x)
return 1
except:
print("Exception")
return 0
finally:
print("this is a finally test")
result = tryTest()
print(result)
Execute try.py
When the input is 1, the program does not catch the exception, then the return value is 1, but before the return will execute the finally statement block, that is, print the sentence "this is a finally test", as follows.
When the input is 0, the program does not catch the divide 0 exception and executes the statement block in except, then the return value is 0, but the statement block in finally is executed before the return, as shown below.
So anyway the code in the finally statement block is executed, if there is a return statement in the finally, then the whole function will return from the return statement in the finally, the previous return statement is useless.