Dalmas
0
Q:

python error handling

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
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:
	#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
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