Python Tutorial Series – Exceptions

Exceptions are used to catch errors during program execution. Catching errors with exceptions during program execution helps prevent a program from crashing.

Exception handling is performed in Python as follows:

 

try:
  do_something()
except:
  print (‘Exception occurred’)

Catch a specific exception:

 

try:
  do_something()
except ValueError:
  print (‘ValueError Exception occurred’)

Catch multiple exceptions:

 

try:
  do_something()
except (ValueError, OSError):
  print (‘Multiple Exceptions occurred’)

 

try:
  do_something()
except ValueError:
  print (‘ValueError Exception occurred’)
except OSError:
  print (‘OSError Exception occurred’)

Use an else statement to perform specific actions when an exception is not thrown:

 

try:
  open_some_file()
except ValueError:
  print (‘ValueError Exception occurred’)
else:
  close_the_file()

Throw an exception:

 

raise NameError(‘Name error exception’)

More Python