Alex
0
Q:

python raise exception

raise Exception("message")
9
except Exception as e: print(e)
18
try:
  print("I will try to print this line of code")
except:
  print("I will print this line of code if an error is encountered")
40
try:
  # Dangerous stuff
except ValueError:
  # If you use try, at least 1 except block is mandatory!
  # Handle it somehow / ignore
except (BadThingError, HorrbileThingError) as e:
  # Hande it differently
except:
  # This will catch every exception.
else:
  # Else block is not mandatory.
  # Dangerous stuff ended with no exception
finally:
  # Finally block is not mandatory.
  # This will ALWAYS happen after the above blocks.
11
>>> def catch():
...     try:
...         asd()
...     except Exception as e:
...         print e.message, e.args
... 
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)
8
# Raise is used to cause an error
raise(Exception("Put whatever you want here!"))
raise(TypeError)
7
import sys
try:
	S = 1/0 #Create Error
except: # catch *all* exceptions
    e = sys.exc_info()
    print(e) # (Exception Type, Exception Value, TraceBack)

############
#    OR    #
############
try:
	S = 1/0
except ZeroDivisionError as e:
    print(e) # ZeroDivisionError('division by zero')
2
try:
  # code block
except ValueError as ve:
  print(ve)
10
>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
7

  try:
  print(x)
except NameError:
  print("Variable x 
  is not defined")
except:
  print("Something else went 
  wrong") 
2
class MyError(TypeError):
    pass

raise MyError('An error happened')
0
	# this raises a "NameError"

>>> raise NameError('HiThere')

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

New to Communities?

Join the community