+ 2
What is Try-except-else ? Explain
2 Respostas
+ 4
With the help of try-except and try-except-else, you can avoid many unknown problems that could arise from your code.
Like below:
int(input('Enter interger:'))
if user inputs string then error will be shown on screen.
To prevent that, try-except -else-finally those are used to get rid of any problem occurance that could arise if user try to do something werid. like if integer is required as input entering string... Exception can be shown by just using print and giving user message or by exception raising using except DivisionbyZero..etc as required.
try-except-finally
Example:
try:
int(input('Enter an integer'))
except:
print('Error: Not an integer!')
finally:
print('No matter what above happens this will be printed')
try-except-else:
Example:
while True:
# Enter integer value from the console.
x = int(input())
# Divide 1 by x to test error cases
try:
result = 1 / x
except:
print("Error case")
exit(0)
else:
print("Pass case")
exit(1)
0
If an error occurs inside try block, the code inside except block will be executed.
If no exception is raised, then the code inside the else block will be executed.
As a bonus, code inside finally block will always be executed, after all the others.
Happy coding!