Yuval
Yuval

Reputation: 71

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?

Upvotes: 1

Views: 7245

Answers (3)

Blaack Work
Blaack Work

Reputation: 29

You CAN use try except to catch ANY error without worrying for its types. Use this code

try:
    blah blah
except Exception as A: #(Where A is a temporary variable)
    print(a)

Tadaaa, you just captured the error without blowing your whole code.

Upvotes: 0

KingsDev
KingsDev

Reputation: 660

You can use traceback, more specifically traceback.print_exc(). This prints the full error traceback, rather than just the one line produced from using as in your except block.

I've put an example below using a ValueError.

import traceback

try:
    int("s")
except ValueError:
    traceback.print_exc()

This produces the same print result as if there was no try-except, the difference being that this solution allows the code to continue running.

Upvotes: 1

Vazno
Vazno

Reputation: 71

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' 

Upvotes: 2

Related Questions