+ 1
If I have a code that accept user input then do a function, the error might varry depending on user input. how do we handle the exceptions considering we don't know which one? How to handle all exceptions.
example def SumInput(): in1 = int(input('Give first input: ') in2 = int(input('Give second input: ') print(in1 + in2)
7 ответов
+ 2
You can handle different exceptions like so:
try:
...
except ZeroDivisionError:
...
except (NameError, TypeError):
...
except:
...
+ 1
Just use 'except:' without exception id and it will catch all possible exceptions. Something like this:
def SumInput():
try:
in1 = int(input('Give first input: ')
in2 = int(input('Give second input: ')
print(in1 + in2)
except:
print("unknown error")
+ 1
Thank you @Textobot. what if I intended to communicate to the user what the problem with their input was? Not just a general statement.
+ 1
@Martin Cornel
Than You should use approach posted by @Zen.
+ 1
I thought of this approach:
using an if selection segment in the except statement that catches all errors.
within the series of if statement, i would test for input type then print the necessary error message to the user to explain to them what they did wrong in their input.
+ 1
Wow! I've learnt a lot from that reply! @Textobot
0
@Martin Cornel Using 'if' in except section seems to be tricky and some things can't be checked rapidly using 'if' only. Imagine you've read string variable like:
xstr = input("enter x:")
And now you want to convert it to integer like this:
x = int(xstr)
It will cause error if xstr string is not representing integer. To avoid error raising again, you need to write function which checks that all string's symbols are digits and first non sign symbol is in 1..9. You may check it symbol by symbol, or it can be easily done with Python Regex, using pattern ^(0|((-|+)?[1-9]+[0-9]*))$, but it brings unnecessary complexity even to small function like SumInput. Imagine what this approach will bring to larger functions with a lot of input and more complex data.
As The Zen of Python says:
Simple is better than complex.
Flat is better than nested.
So I would say that using 'if' for dealing with error types in except section should be avoided and @Zen's approach is the best here.