+ 1

[Python] If/Else vs. Try/Except

When do people use try/except statements (over if/else statements)? In the case of the attached code, would it be better to use try/except statements or if/else statements? https://code.sololearn.com/c11IJ22040wR/?ref=app

28th Nov 2019, 3:26 PM
Zerokles
Zerokles - avatar
10 Respostas
+ 2
In try/except, you are saying to try to do something, but if an error happens, do what is under except
28th Nov 2019, 3:57 PM
Isaac Tate
Isaac Tate - avatar
+ 2
Try/except seems to require 40 times more runtime to handle zerodivision error than it takes with if else.
28th Nov 2019, 6:55 PM
Seb TheS
Seb TheS - avatar
0
Yes, handling an error with try except can require 40× more runtime than preventing an error to happen: https://code.sololearn.com/cDs2obO7wFL2/?ref=app
28th Nov 2019, 7:07 PM
Seb TheS
Seb TheS - avatar
0
Does the same go for KeyError?
28th Nov 2019, 7:31 PM
Zerokles
Zerokles - avatar
0
Zerokles If you are talking to me, then yes, it is better to check whether they key is in the dictionary with in operator for example. if key in dict: dict[key] Or you can also use the dictionary get method, which returns None if the searched key is not found: dict.get(key)
28th Nov 2019, 7:44 PM
Seb TheS
Seb TheS - avatar
0
Seb TheS Thanks
28th Nov 2019, 7:46 PM
Zerokles
Zerokles - avatar
0
If and else are for conditional statement while try and except are for handling exceptions or errors
29th Nov 2019, 10:14 AM
Helix
0
If/else uses a condition to decide which code to use, try/except uses errors, and can be more specific with the error. The try/except also has a optional finally that is used whenever the program is run, regardless of whichever code was performed. An if/else statement is like: if 3==3: //Code here Else: //Code here A try/except is more like: try: //code here Except: /optional error here //code here //Optional Finally: //Code here
29th Nov 2019, 4:01 PM
Apollo
0
I know try/except statements are for catching exceptions. I was just wondering when they would be more favorable to use over if/else since you can check some of them through if/else anyway. Example: try, except ZeroDivisionError can be replaced by if divisor != 0, else try, except TypeError can be replaced by if type(variable) == int, else
30th Nov 2019, 4:58 AM
Zerokles
Zerokles - avatar