How to use Python try…except…finally

Introduction to Python try…catch…finally statement

  • The finally clause always executes whether an exception occurs or not. And it executes after the tryexceptstatement.
try:
# code that might cause exceptions
except:
# code that handle exceptions
finally:
# code that always executes

Python try … finally statement

try:
# code that might cause exceptions
finally:
# code that always executes

Python try … else statement

# program to print the reciprocal of even numbers

try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!!!")
else:
reciprocal = 1/num
print(reciprocal)

output

  • If we pass an odd number:
Enter a number: 5
Not an ever number!!!
  • If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
  • But, if we pass 0, we will get ZeroDivisionError as the code block insde else is not handled by except
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero

Specific Exceptions

try:
print (x)
except NameError:
print ("Parameter x is not defined!")
except:
print ("Something else went wrong!")
try:
# do something
pass

except ValueError:
# handle ValueError exception
pass

except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass

except:
# handle all other exceptions
pass

Summing Up

  • In the try clause, all statements are executed until an exception is encountered.
  • except is used to catch and handle the exception(s) that are encountered in the try clause.
  • else lets you code sections that should run only when no exceptions are encountered in the try clause.
  • finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store