0

If have a function were I request some data from a website but when I get an error I want to print the error and restart my code. But I don't know the exact code, can please someone help me? This is a code example:

import time
input1 = input("Blabla: ")

def repeat():
    try:
        if input1 == "123":
            raise "Error: 123"
    except Exception as e:
        print(e)
        time.sleep(5) # Wait 5 seconds
        repeat() # Rerun code

repeat()

When I run this code I get the error 'exceptions must derive from BaseException'. Can someone help me?

3
  • 3
    Don't use a recursive call to "restart your code". Use a loop, that's what they're for. Commented Apr 1, 2019 at 20:01
  • 2
    You also probably want to move input1 = input("Blabla: ") inside of your function (otherwise, this value never changes when you recurse) Commented Apr 1, 2019 at 20:02
  • Since you always catch the exception, and you only want to print it out, it might also make more sense not to raise an exception at all. Instead, you could just print("Error: 123") directly. Commented Apr 1, 2019 at 20:05

2 Answers 2

6

You can't just raise random strings as an exception. If you want to raise a general exception without defining a relevant type, just raise Exception, replacing:

raise "Error: 123"

with:

raise Exception("Error: 123")  # The "Error: " should probably be removed

Alternatively, if you can use a more specific error, do so. If 123 is invalid because the value is wrong, use ValueError instead of Exception. If there is some more specific reason, make a subclass to make it easier for others to catch, e.g. (at top level in the module):

class SpecialValueError(ValueError):
    pass

so you can do:

raise SpecialValueError("Error: 123")

and people can catch it specifically, or via plain except ValueError:, except Exception:, etc.

Sign up to request clarification or add additional context in comments.

2 Comments

I somehow miss mentioning the __str__() method of the derived exception class, since printing the exception was asked for.
@guidot: I'm not sure what you mean by that. BaseException provides a useful default __str__ (it's just whatever message you passed as the first argument); it's pretty rare that you need to define a replacement __str__, but there's nothing preventing it.
0

Right now you are printing the error object's str while you need to print it's representation

Try this:

def repeat():
    try:
        if input1 == "123":
            raise Exception("Error: 123") # You need to use an Exception class
    except Exception as e:
        print(repr(e)) # Notice I added repr()
        time.sleep(5)
        repeat()

Exception's Representation vs Exception's String

String:

try: 
    raise Exception("Exception I am!") 
except Exception as e: 
    print(e) 
# Output: Exception I am!

Representation:

try: 
    raise Exception("Exception I am!") 
except Exception as e: 
    print(repr(e)) 

# Output: Exception('Exception I am!')

1 Comment

That's kind of a side issue from the OP's problem (failing to actually raise a real exception type). Why do you think the repr is needed? That would just add unnecessary quotes around the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.