Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a statement to be executed after raise in python?

I found following code in TwistedSNMP library:

try:
  raise ImportError
  import psyco
except ImportError, err:
  pass
else:
  from pysnmp.asn1 import base
  psyco.bind(base.SimpleAsn1Object)  psyco.bind(base.Asn1Object)

Source filename: pysnmpproto.py, Line 42

Are there any cases that either import psyco or else block will ever be executed?

like image 666
Vikas Avatar asked Apr 23 '12 12:04

Vikas


People also ask

Does raise in Python stop execution?

The effect of a raise statement is to either divert execution in a matching except suite, or to stop the program because no matching except suite was found to handle the exception. The exception object created by raise can contain a message string that provides a meaningful error message.

Does finally execute after raise?

It defines a block of code to run when the try... except...else block is final. The finally block will be executed no matter if the try block raises an error or not. This can be useful to close objects and clean up resources.

What does raise statement 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.

What happens when a raise statement is encountered in a function?

What happens when a raise statement is encountered in a function? The code executes the next line in the function. The raise exception is printed immediately.


1 Answers

import psyco will never be reached because of the exception raised on the previous line. The exception will be caught by the except clause, which in this case does nothing. The else clause will never be reached because you only reach it if your try clause executed without exceptions.

In short, this code will always raise an exception, catch it, and do nothing else. It should be deleted.

like image 146
Steven Rumbalski Avatar answered Oct 22 '22 02:10

Steven Rumbalski