Try Statements in Python (Python Part 12)

This class will teach yo how to use Try Statements. This allows you to try to take an action with an API, or OS command and if it does not work then do something else.

  • 00:00 Intro
  • 09:25 Try / Except Statement
  • 13:59 Finally
  • 16:55 Else
  • 20:02 Exceptions and Errors
  • 23:49 Built-In Exceptions
  • 35:59 Final Thoughts

try.py

message = 'hello students'

try:
  print(message)
except:
  print('FAIL')
  #pass

finished.py

name = input('Your name: ')

try:
  print(f'Hello {name}')
except:
  print('There was an error')
finally:
  print('The script is finished')

else.py

name = input('Your name: ')

try:
  print(f'Hello {name}')
except:
  print('There was an error')
else:
  print('Im happy to meet you')
finally:
  print('The script is finished')

exception.py

name = input('Your name: ')

try:
  print(f'Hello {name}')
except Exception as error:
  print(error)
else:
  print('Im happy to meet you')
finally:
  print('The script is finished')

built-in-exceptions.py

file_name = 'file.txt'

try:
  file = open(file_name, 'r')
  data = file.read()
  file.close()
except NameError as name_error:
  print(name_error)
except FileNotFoundError as file_error:
  print(file_error)
else:
  print(data)
finally:
  print('The script is finished')

file.txt

hello fellow students. isnt this a cool class?

Be the first to comment

Leave a Reply