
Python Exception Handling
Python Exception Handling
- Python has many built-in exceptions which handles a program and throw error on console if program is not properly working
- When these exception error occurs, python should handle this exception properly to avoid program crash
- It is used to handle errors in python.
- Raise an exception in your program by using the raise exception statement.
Exception Errors:
Exception Name |
Definition |
Exception | It is a class for all exceptions |
Stop iteration | It rises when next() method of an iterator does not point to any yield object |
SystemExit | Raised by sys.exit() function. |
StandardError | Base class for all built-in exceptions except StopIteration and SystemExit. |
ArithmeticError | Base class for all errors that occur for arithmetic calculation. |
ImportError | Raised when an import statement fails. |
IndexError | Raised when an index is not found in a sequence of list or tuple. |
IOError |
Raised when an input/ output operation fails, such as the print statement etc…. |
SyntaxError | Raised when there is an syntax error in script |
IndentationError | Raised when indentation is not specified correctly. |
TypeError | Raised when an operation or function is attempted that is invalid for the specified data type. |
ValueError | Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. |
RuntimeError | Raised when a generated error does not comes into any category |
Examples for Exception Error:
How to Handle an Exception Error:
try-except exception:
‘try’ and ‘except’ are Python identifiers which is used to handle this exceptions.·
Syntax:
Example:
try-finally Exception:
It is intended to define actions that should be execute under all circumstances· A finally clause is always executes before leaving the try statement, whether an exception has occurred previously or not.