Home > Enterprise >  Unable to get error when using "try" and "except" option in Python
Unable to get error when using "try" and "except" option in Python

Time:07-07

I am trying to run a code to show other errors except TypeError.

The code I am using is as below:

A = 1
B = "2"
try:
    C = A   B   D
except TypeError:
    print("Type Error")

Output expected is as below:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-6b5697b50966> in <module>
      1 A = 1
      2 B = 2
----> 3 C = A   B   D

NameError: name 'D' is not defined

However, the actual output is as below:

Type Error

Can someone please suggest the solution for the same?

CodePudding user response:

I tried to remove the try-except and got this error:

TypeError: unsupported operand type(s) for  : 'int' and 'str'

Explanation: you have already caught an error trying to add A and B, therefore your code will stop executing and not find the second error.


Edit: As suggested in the comment, the NameError will show if you first add A and D and then B: A D B

Edit2: If you think you might have different kinds of errors one possibility (if you for example want different things to happen on a specific type of error) is to have multiple excepts like this:

A = 1
B = "2"
try:
    C = A   D   B
except NameError:
    print("ERROR: NameError")
except TypeError:
    print("ERROR: TypeError")

Which produces this output:

ERROR: NameError

CodePudding user response:

Python will first evaluate A B and then add D. Therefore, before noticing that D is not defined and throwing a NameError python will throw a TypeError because the -operator is not applicable to integers and strings.

  • Related