Try and Except conditional statements

05 min read

There are certain situations where an error might occur during the execution of the program which would eventually terminate the program from executing further. In order to avoid such a termination, we could add 'try and except conditionals' to skip the errors and execute the program till the end.

Syntax for 'try and except' conditional statements

try:
body
except:
body


The try loop is executed first, if an error is seen in this part of the program except loop is executed. If there is no error, then except loop is not executed at all.

To understand better, let us consider an example,

Task: check if an input value is an integer or string using try and except statement.

Solution:

test= input('Enter what you want')                           # anything taken from the input() command is default string. 
try:
a=int(test) # only a numeric string can be converted to an integer. int('123')=123 whereas int('hello123') results an error message
print('it is a number') # during conversion of string to int, if no error is popped then it is obviously a number. If error is popped, this statement is not executed.
# if there is an error calculating 'a', try loop is exited and except loop is executed.
except:
print('it is not a number') # if the input() was not able to be converted in the try statement, then it is obviousy not an integer.


POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error