python raise value error code example

Example 1: how to print error in try except python

try:
  # some code
except Exception as e:
	print("ERROR : "+str(e))

Example 2: raise exception in python

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

Example 3: raise python

# Raise is used to cause an error
raise(Exception("Put whatever you want here!"))
raise(TypeError)

Example 4: error handling Pyhtin

# taking input from the user 
try:
    age = int(input("Please enter your age: "))
    print(age)
except:
    print("please enter a number instead! ")
    print('bye')


# if you wanna ask their age until they enter the correct number use While Loop
while True:
    try:
        age = int(input("Please enter your age: "))
        print(age)
    except:
        print("please enter a number instead! ")
    else:
        break

Example 5: try except python

try:
  print("I will try to print this line of code")
except ERROR_NAME:
  print("I will print this line of code if error ERROR_NAME is encountered")

Example 6: python raise exception

# this raises a "NameError"

>>> raise NameError('HiThere')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere

Tags:

Misc Example