Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

  1. Is there a performance or code maintenance issue with using assert as part of the standard code instead of using it just for debugging purposes?
    Is assert x >= 0, 'x is less than zero' better or worse than if x < 0: raise Exception, 'x is less than zero'

  2. Also, is there any way to set a business rule like if x < 0 raise error that is always checked without the try/except/finally so, if at any time throughout the code x is less than 0 an error is raised, like if you set assert x < 0 at the start of a function, anywhere within the function where x becomes less then 0 an exception is raised?

1 Answer

0 votes
by (106k points)
  • In Python asserts is used to test conditions that should never happen. The main purpose of using assert is to crash early in the case of a corrupt program state.
  • While exceptions are used for handling errors that can probably happen, and it is advised that you should always create your own Exception classes.
  • We will understand these points by an example, if you're writing a function to read from a configuration file into a dict, improper formatting in the file should raise a ConfigurationSyntaxError, on the other hand, you can assert that you're not about to return None.
  • The example that you have mentioned in that case, if x is a value set via a user interface or from an external source, an exception is best.  In your code, if x is only set then go with an assertion.

Related questions

0 votes
1 answer
asked Jul 26, 2019 in Python by selena (1.6k points)
+1 vote
1 answer
0 votes
1 answer

Browse Categories

...