1.

What is the difference between assertion and exception? Explain with the help of suitable Python examples.

Answer»

People often get confused between assertions and exceptions and often use the LATTER when the former should be used in a program (and vice versa).

The fundamental difference lies in the nature of the error to be caught and PROCESSED. Assertion is a statement of something that MUST be TRUE. If not, then the program is terminated and you cannot recover from it. Exception on the other hand is a runtime situation that can be recovered from.

Python’s assert statement checks for a condition. If the condition is true, it does nothing and your program just continues to execute. But if it evaluates to false, it raises an AssertionError exception with an optional error message.

>>> def testassert(x,y): TRY: assert y!=0 print ('division', x/y) except AssertionError: print ('Division by Zero not allowed') >>> testassert(10,0) Division by Zero not allowed

The PROPER use of assertions is to inform developers about unrecoverable errors in a program. They’re not intended to signal expected error conditions, like “file not found”, where a user can take corrective action or just try again. The built-in exceptions like FileNotFoundError are appropriate for the same.

You can think of assert as equivalent to a raise-if statement as follows:

if __debug__:     if not expression1:         raise AssertionError(expression2)

__debug__ constant is true by default. 

Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors for which exceptions can be used.

Assertion can be globally disabled by setting __debug__ to false or starting Python with -O option.

$python -O >>> __debug__ False


Discussion

No Comment Found