9

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.

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
James
  • 103
  • 1
  • 2
  • 6

3 Answers3

12

The syntax is:

raise Exception("Invalid level! " + level)

I would really recommend you to read the Python docs.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

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

Joan Smith
  • 931
  • 6
  • 15
  • Oh, yes. But I can't accept it right now.. I have to wait few more minutes before I can do that. – James Mar 17 '14 at 04:26
  • But I don't know which one to choose, sorry. I have no idea which answer is more relevant to me. Both have helped me. – James Mar 18 '14 at 00:14
  • @James, Doesn't matter too much :) Just pick one so that the question can be marked as closed – Joan Smith Mar 18 '14 at 01:25
1

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)
Lemons
  • 379
  • 4
  • 14