Like other languages, python also provides the runtime errors via exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.
Example 1:
# Python program to handle simple runtime error a = [1,2,3] try:print("Second element = %d"%(a[1]))# Throws error since there are only 3 elements in array print("Fourth element = %d"%(a[3]) )exceptIndexError:print("An error occurred")
Second element = 2
An error occurred
Example 2:
# Program to handle multiple errors with one except statement try: a =3if a <4:# throws ZeroDivisionError for a = 3 b = a/(a-3) # throws NameError if a >= 4 print("Value of b = ", b)# note that braces () are necessary here for multiple exceptions except(ZeroDivisionError,NameError):print("\nError Occurred and Handled")
Error Occurred and Handled
Else Clause
Example 3:
# Program to depict else clause with try-except # Function which returns a/b defAbyB(a,b): try: c = ((a+b) / (a-b)) exceptZeroDivisionError:print("a/b result in 0")else:print(c)finally:print("success")# Driver program to test above function AbyB(2.0, 3.0)AbyB(3.0, 3.0)
-5.0
a/b result in 0
success
Example 4:
import sysrandomList = ['a',0,2]for entry in randomList:try:print("The entry is", entry) r =1/int(entry)breakexcept:print("Oops!",sys.exc_info()[0],"occured.")print("Next entry.")print()print("The reciprocal of",entry,"is",r)