By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Python language has two very important features to handle any unexpected error that may occur while executing the Python programs and to add debugging capabilities in them. Those features are as follows.
- Exception Handling: While writing a Python code, if we have a feeling that have some part of the code may raise an exception then we can handle that part by placing the code in a try: block. After the try: block, include an except: statement, followed by a block of code that handles the problem as effectively as possible.
Syntax is given below.
try: We do our operations here; ......................
except Exception I: If Exception I, then execute this block.
except Exception II: If Exception II, then execute this block. ......................
else:If no exception then execute this block.
Few points to remember about Python exception handling. A single try statement can have multiple except statements. This feature can be well utilized when the try block contains statements that may throw more than one and different types of exceptions. It supports feature to provide a generic except clause, which can handle any type of exception. Syntactically, we can include an else-clause after the except clause(s). The code in the else-block will be executed only if the code in the try: block does not raise an exception.
The else-block is a useful programming place for code that does not need the try: block's protection.
Below is a list of standard Exceptions available in Python programming language.
EXCEPTION NAME
DESCRIPTION
Exception
This exception is the base class for all exceptions.
StopIteration
This exception is raised when the next () method of an iterator does not point to any object.
SystemExit
This exception is raised by the sys.exit () function.
StandardError
This exception is the base class for all built-in exceptions except SystemExit and StopIteration.
ArithmeticError
This exception is the base class for all errors that occur for numeric calculation.
OverflowError
This exception is raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
This exception is raised when a floating point calculation fails.
ZeroDivisonError
This exception is raised when division or modulo by zero takes place for all numeric types.
AssertionError
This exception is raised in case of failure of the Assert statement.
AttributeError
This exception is raised in case of failure of attribute reference or assignment.
EOFError
This exception is raised when there is no input from either the raw_input () or input () function and the end of file is reached.
ImportError
This exception is raised when an import statement fails.
KeyboardInterrupt
This exception is raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError
This exception is the base class for all lookup errors.
IndexError
Raised when an index is not found in a sequence.
KeyError
This exception is raised when the specified key is not found in the dictionary.
NameError
This exception is raised when an identifier is not found in the local or global namespace.
UnboundLocalError
This exception is raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError
This exception is the base class for all exceptions that occur outside the Python environment.
IOError
This exception is raised when an input/ output operation fails, such as the print statement or the open () function when trying to open a file that does not exist.
This exception is raised for operating system-related errors.
SyntaxError
This exception is raised when there is an error in Python syntax.
IndentationError
This exception is raised when indentation is not specified properly.
SystemError
This exception is raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
This exception is raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
ValueError
This exception is raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
RuntimeError
This exception is raised when a generated error does not fall into any category.
NotImplementedError
This exception is raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
Python example on exception handling.
The try-finally Clause Finally is the block that comes at the last and is always executed irrespective of exception occurred or not. This is demonstrated in the below example. - Assertions: An assertion in Python can be defined as a sanity-check that can turn on or turn off when we are done with the testing of the program. An expression is tested for the result, and if that comes up false, an exception is raised. Below is the syntax for assertions. assert Expression[, Arguments] If the assertion fails, Python will use an ArgumentExpression as the argument for the AssertionError. AssertionError is an exceptions that can be caught and handled like any other exception using the try-except statement If this exception is not handled, then it will terminate the program and produce a traceback as shown in the below example.
Given below is an example on Python Assertion, where we are checking for account balance if it is lower than minimum balance of 5000. During first test for balance of 500, it passed the test therefore no AssertionError happened. However, in the second case the input balance is 1000 which is less than minimum balance therefore AssertionError was raised in the console with our pre-defined message string (Account is in good condition above minimum balance).
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.