Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an exception in Python 3.3

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.

like image 669
James Avatar asked Mar 17 '14 04:03

James


People also ask

How do you raise exceptions in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

What does raise () do in Python?

Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.

How do I manually raise exceptions?

Throwing exceptions manually There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class. To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.


1 Answers

The syntax is:

raise Exception("Invalid level! " + level)

I would really recommend you to read the Python docs.

like image 199
Christian Tapia Avatar answered Oct 02 '22 04:10

Christian Tapia