0

Can anyone explain me how try,except block works in python?

I don't get it.

17th Apr 2020, 7:52 PM
Yin Yin Htoo
Yin Yin Htoo - avatar
2 RĂ©ponses
+ 2
"try" simply contains a block of code to be executed until the first error (if any) occurs, then it moves to the "except" block to execute the code in it. a = int(input()) b = int(input()) try: print(b / a) print("successful") except ZeroDivisionError: print("zero cannot be the divisor") except: print("only integers are valid") We specified the type of error that might occur in our case which is dividing by zero and told python to send a message to the user instead of that error that pops up We also don't know if the user would put anything other than an integer, so we specified a general exception that tells Python in that case to send a message asking for integers Notice that in case of an error in the first line in the "try" block, the second print function won't be executed, because we moved to the "except" block. hope it helps. You may want to read that part in the Python course for better understanding.
17th Apr 2020, 8:19 PM
Ali Abdelhady
Ali Abdelhady - avatar
0
It is explained in the lesson. https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2441/ When you have difficulity with a topic, try also reading the comments below each lesson, and experiment with the sample code in the playground. It might help more than words.
18th Apr 2020, 3:30 AM
Tibor Santa
Tibor Santa - avatar