Exception Handling in Python
Sometimes while executing a Python program, the program does not execute at
all or the program executes but generates unexpected output or behaves
abnormally. These occur when there are syntax errors, runtime errors or logical
errors in the code. In Python, exceptions are errors that get triggered
automatically .
However, exceptions can be forcefully triggered and handled through program
code.
Handling Exceptions
An exception is a Python object that represents an error. When an error occurs
during the execution of a program, an exception is said to have been raised. Such
an exception needs to be handled by the programmer so that the program does
not terminate abnormally. Therefore, while designing a program, a programmer
may anticipate such erroneous situations that may arise during its execution and
can address them by including appropriate code to handle that exception.
• Python’s standard library is an extensive collection of built-in exceptions
that deals with the commonly occurring errors (exceptions) by providing
the standardized solutions for such errors.
• On the occurrence of any built-in exception, the appropriate exception
handler code is executed which displays the reason along with the raised
exception name.
• A programmer can also create custom exceptions to suit one’s
requirements. These are called user-defined exceptions.
• Programmers can also forcefully raise exceptions in a program using the
raise and assert statements. Once an exception is raised, no further
statement in the current block of code is executed.
Raise statement:
• The assert Statement
An assert statement in Python is used to test an expression in the program
code. If the result after testing comes false, then the exception is raised.
This statement is generally used in the beginning of the function or after a
function call to check for valid input.
The syntax for assert statement is:
• assert Expression[,arguments]
• On encountering an assert statement, Python evaluates the expression
given immediately after the assert keyword. If this expression is false, an
AssertionError exception is raised which can be handled like any other
exception.