paul
0
Q:

python file open try except error

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
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
# Python code to illustrate 
# working of try()  
def divide(x, y): 
    try: 
        # Floor Division : Gives only Fractional Part as Answer 
        result = x // y 
        print("Yeah ! Your answer is :", result) 
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero ") 
  
# Look at parameters and note the working of Program 
divide(3, 0) 
8
def FileCheck(fn):
    try:
      open(fn, "r")
      return 1
    except IOError:
      print "Error: File does not appear to exist."
      return 0

result = FileCheck("testfile")
print result
0

New to Communities?

Join the community