0
Q:

error handling in python

try:
  print("try to run this block")
except:
  print("run this bock if there was error in earlier block")
15
except Exception as e: print(e)
18
>>> 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
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")
21
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
   1 import sys
   2 try:
   3   untrusted.execute()
   4 except: # catch *all* exceptions
   5   e = sys.exc_info()[0]
   6   write_to_page( "<p>Error: %s</p>" % e )
4
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
try:
	#insert code here
except:
	#insert code that will run if the above code runs into an error.
except ValueError:
	#insert code that will run if the above code runs into a specific error.
	#(For example, a ValueError)
1
# Use 'try' to handle exceptions:
try:
  code_to_try()
except <exception, i.e. ValueError>:
  do_this()
# You can add an else: or finally: statement for other branching
4
try:
  print(x)
except SyntaxError:
  print("There is a SyntaxError in your code")
except NameError:
  print("There is a NameError in your code")
except TypeError:
  print("There is a TypeError in your code")
0

New to Communities?

Join the community