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. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

8th Sep 2016, 9:19 AM
Cornel
Cornel - avatar
7 Answers
+ 2
You can handle different exceptions like so: try: ... except ZeroDivisionError: ... except (NameError, TypeError): ... except: ...
8th Sep 2016, 10:11 AM
Zen
Zen - avatar
+ 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")
8th Sep 2016, 9:27 AM
Textobot
Textobot - avatar
+ 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.
8th Sep 2016, 9:35 AM
Cornel
Cornel - avatar
+ 1
@Martin Cornel Than You should use approach posted by @Zen.
8th Sep 2016, 9:59 AM
Textobot
Textobot - avatar
+ 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.
8th Sep 2016, 1:29 PM
Cornel
Cornel - avatar
+ 1
Wow! I've learnt a lot from that reply! @Textobot
9th Sep 2016, 11:21 AM
Cornel
Cornel - avatar
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.
9th Sep 2016, 6:42 AM
Textobot
Textobot - avatar