+ 2
Try, except and finally
I am struggling to understand where this conditions will come in handy when coding in python.
2 Answers
+ 4
For instance, consider a scenario where user input may cause exceptions in your code.
x = input()
print(1/x)
In this case, an input of 0 will cause problems. Exception handling can be done using try-except blocks.
try:
print(1/input())
except:
print("something went wrong")
# react accordingly
In addition to try and except, you can also add a finally block. The contents in this block will execute regardless if an exception is thrown.
try:
print(1/input())
except:
print("something went wrong")
# react accordingly
finally:
print("try-except completed")
In other situations, you may encounter files which you do not have sufficient permissions to access. A better example of when you'd require a finally block:
try:
 f = open("myFile")
 f.write("something")
except:
  # handle exceptions if any
finally:
 f.close()
# regardless of whether exceptions were caught, always close opened files.
+ 1
Example:
try:
input_ = int(input('Enter: '))
except:
print('Enter integer only: ')
finally:
print('No matter what above happens it will be printed')
As we use try: and inside it we ask user to input number (int - integer)
if user input is not integer it will throw exception as given 'Enter integer only:' ..
If we didn't have used try..except then if user input is not integer the program will throw Traceback Error on conclose.
Note: Exception can be more than one..
eg:
try:
....
except ....
....
except ZeroDivisionError:
....
Also : There is many types of exception that can occur.
like ZeroDivisionError ....and so on.