Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "raise" keyword in Python [duplicate]

I have read the official definition of "raise", but I still don't quite understand what it does.

In simplest terms, what is "raise"?

Example usage would help.

like image 314
Capurnicus Avatar asked Dec 19 '12 17:12

Capurnicus


People also ask

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.

Can we use raise keyword in TRY block?

While the try and except block are for handling exceptions, the raise keyword on the contrary is to raise an exception.

What is the use of raise statement?

The RAISE statement stops normal execution of a PL/SQL block or subprogram and transfers control to an exception handler. RAISE statements can raise predefined exceptions, such as ZERO_DIVIDE or NO_DATA_FOUND , or user-defined exceptions whose names you decide.

How do you handle a raise exception in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.


1 Answers

It has 2 purposes.

jackcogdill has given the first one.

It's used for raising your own errors.

if something: 
    raise Exception('My error!') 

The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.

try:   generate_exception() except SomeException as e:   if not can_handle(e):     raise   handle_exception(e) 
like image 80
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 03:10

Ignacio Vazquez-Abrams