+ 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
9 Respuestas
+ 2
In try/except, you are saying to try to do something, but if an error happens, do what is under except
+ 2
Try/except seems to require 40 times more runtime to handle zerodivision error than it takes with if else.
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
0
Does the same go for KeyError?
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)
0
Seb TheS Thanks
0
If and else are for conditional statement while try and except are for handling exceptions or errors
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
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