Question

I am currently reading tutorials in tutorialspoint's python tutorials. But it's the tutorial of Python 2 not Python 3.3 which I have right now. Well, I managed to search in the internet and found out about some changes. But this one is pretty tough.

So, in tutorialspoint the python source code for raising an exception is:

def functionName( level ):
if level < 1:
   raise "Invalid level!", level
  # The code below to this would not be executed
  # if we raise the exception

But if I type

raise "Invalid level!", level  

it says syntax error. So, I want to know how I raise an exception in Python 3.3.

Was it helpful?

Solution

The syntax is:

raise Exception("Invalid level! " + level)

I would really recommend you to read the Python docs.

OTHER TIPS

You need to create an Exception object:

 raise Exception('spam', 'eggs')

See the docs here: http://docs.python.org/3/tutorial/errors.html#handling-exceptions

For reference, here is a simple example:

# Raise exception if x != 4
try:
    x = 3
    if (x != 4):
        raise Exception('X is not 4')
except Exception as e:
    print('ERROR: ', e)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top