How to Use Try Except Else Finally Statements for Error Handling in Python

Python

 1|  try:
 2|      # try to run process_data function
 3|      process_data()
 4|  
 5|  except Exception as e:
 6|      # if any error occurs, print details of the exception
 7|      print(e)
 8|  
 9|  else:
10|      # if no error occurs print this message
11|      print('Ran Successfully')
12|  
13|  finally:
14|      # Regardless of whether there is an error or not print this message
15|      print('Finished')
16|  
17|  """Other common types of exceptions:
18|  ZeroDivisionError
19|  ModuleNotFoundError
20|  IndexError
21|  KeyError
22|  MemoryError
23|  NameError
24|  FileNotFoundError
25|  PermissionError
26|  TypeError
27|  ValueError
28|  Warning
29|  """
Did you find this snippet useful?

Sign up for free to to add this to your code library