pythontry-except

How do you print an error with Try and Except


I feel stupid asking this since the answer is probably simple but I couldn't really find the answer by googling it... I have a lot of code which I don't want help with, I want to debug on my own, and I use try/except for it, but except doesn't print the error messsage and I couldn't find a way to print that. Basically, how do I check what my error is?


Solution

  • Firstly to check what is your error, you can watch into your terminal there will be error's name:

    print(5+"5")
    
    >>>
    Traceback (most recent call last):
      File "c:\Users\USER\Desktop\how_to_use_try_except.py", 
    line 1, in <module>
        print(5+"5")
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    

    and to catch it, you need to copy error's name, and except it

    try:
        print(5+"5")
    except TypeError:
        print("You can't add string value to int!")
    

    also you can write

    try:
        print(5+"5")
    except TypeError as e:
        print(e)
    >>>
    unsupported operand type(s) for +: 'int' and 'str'