cas
0
Q:

python finally

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:
  x > 3
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
finally:
  print("The try...except block is finished")
2
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
>>> 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:
  # code block
except ValueError as ve:
  print(ve)
10
# 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
x = 1

try:
  y = int(x)

except ValueError:
  print("The variable is not an integer")

else:
  print("Nothing went wrong")

finally:
  print("The try-except block is finished") 
0
# 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
import sys
def my_except_hook(exctype, value, traceback):
    if exctype == KeyboardInterrupt:
        print "Handler code goes here"
    else:
        sys.__excepthook__(exctype, value, traceback)
sys.excepthook = my_except_hook
0

New to Communities?

Join the community