Google News
logo
Python Exceptions
An python exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.  An exception is a Python object that represents an error.

Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.
>>> 5/0
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    5/0
ZeroDivisionError: division by zero
>>> open("myfile.txt")
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    open("myfile.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'
>>> 
Errors can also occur at runtime and these are called exceptions. They occur, for example, when a file we try to open does not exist (FileNotFoundError), dividing a number by zero (ZeroDivisionError), module we try to import is not found (ImportError) etc.
EXCEPTION DESCRIPTION
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any object.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
TabError Raised when indentation consists of inconsistent tabs and spaces.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it.
IOError

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.

Raised for operating system-related errors.

SyntaxError Raised when there is an error in Python syntax.
SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
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 fall into any category.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
IndentationError Raised when indentation is not specified properly.
GeneratorExit Raise when a generator's close() method is called.
OSError Raised when system operation causes system related error.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
Python Exception Handling :

Exception in a code can also be handled. In case it is not handled, then the code is not executed further and hence execution stops when exception occurs.

The suspicious code can be handled by using the try block. Enclose the code which raises an exception inside the try block. The try block is followed except statement. It is then further followed by statements which are executed during exception and in case if exception does not occur.

try:  
    malicious code  
except Exception-1:  
    execute code  
except Exception-2:  
    execute code  
....  
....  
except Exception-N:  
    execute code  
else:  
    In case of no exception, execute the else block code.  
>>> try:
	a=16/0
	print (a)
except ArithmeticError:
	print ("This statement is raising an exception " )
else:
	print ("Free Time Learning")

	
This statement is raising an exception 
>>> 

Declaring Multiple Exception

You can also use the same except statement to handle multiple exceptions as follows :

try:
   your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block.

Raising an Exceptions

In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.

You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows :

>>> try:
	 a=10
	 print (a)
	 raise NameError("FTL")
except NameError as e :
	print ("An exception occurred")
	print (e)

	
10
An exception occurred
FTL
>>> 

try...finally

The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources.

The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is following :

>>> try:
	a=8/0;
	print ("Exception occurred")
finally:
	 print ("Code to be executed")

	 
Code to be executed
Traceback (most recent call last):
  File "<pyshell#54>", line 2, in <module>
    a=8/0;
ZeroDivisionError: division by zero
>>>