Python Exceptions Handling

Python Exceptions Handling is used to remove errors in the Python language. Errors are the problems in a program due to which the program will stop the execution. In Python, there are two very important features to handle any unexpected error in your Python programs and to add debugging capabilities to them.

  • Python Exception Handling
  • Assertions
Python Exceptions:

Exceptions occur when the program is syntactically correct but the code resulted in an error. Due to this error execution of the program does not stop, but, it changes the normal flow of the program.

Here is the list of some exceptions name with their description,

Exception NameDescription
ExceptionBase class for all exceptions
StopIteration
Raised when the next() method of an iterator
does not point to any object.
SystemExitRaised by the sys. exit() function.
OverflowError
Raised when a calculation exceeds the maximum limit for a numeric type.
ZeroDivisionError
Raised when a division or modulo by zero takes place for all numeric types.
StandardErrorBase class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
Base class for all errors that occur for numeric calculation.
FloatingPointError
Raised when a floating-point calculation fails.
AssertionError
Raised in case of failure of the Assert statement.
EOFError
Raised when there is no input from either the raw_input()
or input() function and the end of the file is reached.
ImportError
Raised when an import statement fails.
AttributeError
Raised in case of failure of attribute reference or assignment.
LookupErrorBase class for all lookup errors.
IndexError
Raised when an index is not found in a sequence.
KeyboardInterrupt
Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
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.
EnvironmentErrorBase class for all exceptions that occur outside
the Python environment.
IndentationError
Raised when indentation is not specified properly.
UnboundLocalError
Raised when trying to access a local variable in a function
or method but no value has been assigned to it.
SyntaxError
Raised when there is an error in Python syntax.
IOErrorRaised 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.
IOErrorRaised for operating system-related errors.
SystemErrorRaised when the translator finds an inner issue,
but when this error is experienced the Python translator does not exist.
TypeErrorRaised when an operation or function is attempted
that is invalid for the specified data type.
SystemExitRaised when Python interpreter is quit by using the sys. exit() function.
If not handled in the code, causes the interpreter to exit.
ValueErrorRaised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid values specified.
NotImplementedError
Raised when an abstract method that needs to be
implemented in an inherited class is not actually implemented.
RuntimeError
Raised when a generated error does not fall into any category.

Assertions:

The Assertion in Python is one that asserts or tests the trueness of a condition in your code. An Assertion could be a sanity-check that you simply can turn on or turn off once you are done together with your testing of the program. The most effortless way to think of an assertion is to compare it to a raise-if statement. An expression is tried, and in the event that the result comes up wrong, a special case is raised. It is generally utilized to investigate/debug the files within the code and coordinate/match them within the library.

Assert Statement:

Python has a built-in Assert statement to use assertion condition in the program. Here in the Assert statement, there is a condition or expression which is supposed to be true always. If the condition is false assert halts the program and gives an Assertion error.

In Python program Assert statement can be used in two methods,

1)- Assert statement has a condition and if the condition is not satisfied the program will stop and give Assertion error.

Syntax for Assert in Python:

Example using above mentioned assert without error message:
def sum(values):
    assert len(values) != 0
    return sum(values)/len(values)

value1 = []
print("sum of value1:",sum(value1))

2)- Assert statements can also have a condition and an optional error message. If the condition is not satisfied assert stops the program and given an assertion error along with the error message.

Syntax,
Example using above mentioned assert with error message:
#program with error messages
def sum(values):
    assert len(values) != 0, "List is empty."
    return sum(values)/len(values)
value2 = [78+0+11+40]
print("Sum of value2:",sum(value2))

value1 = []
print("sum of value1:",sum(value1))

Exception Handling:

In the event that you have got a few suspicious codes that will raise a special case, you’ll be able to protect your program by setting the suspicious code in an attempt/try: block. After the attempt: square, incorporate an but: articulation, taken after by a square of code which handles the issue as carefully as possible.

Syntax,
try:
   You do your operations here;
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 
try:
   fh = open("testfile", "w")
   fh.write("This is demo file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Exception handling in python"
   fh.close()

This example is to open a file where there do not have any written permission, so it raises an exception .

try:
   fh = open("testfile", "r")
   fh.write("This is test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Exception handling in python"

The except Clause with No Exceptions:

The except Clause with No Exceptions can be used in following pattern,

The except Clause with Multiple Exceptions:

The except Clause with Multiple Exceptions can be used in following pattern,

The try-finally Clause:

finally: block can be used along with a try: block. 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 as given below,

Along with a finally clause we can’t use else clause. understand this code with this example,

#try finally clause program

try:
   fh = open("demofile", "r")
   fh.write("This is demo file for exception handling")
finally:
   print "Error: can\'t find demo file or read given data"

look in to following example for more understanding,

#example 2
try:
   fh = open("demofile", "w")
   try:
      fh.write("This is demo file for exception handling")
   finally:
      print " the file is Going to close "
      fh.close()
except IOError:
   print "Error: can\'t find demo file or given data"

User-Defined Exceptions:

One thing that Python offers you to use exceptions more is that it allows you to create your own exceptions by deriving classes from the standard built-in exceptions.

Here is the example for RuntimeError.  This is useful when you need to display more specific information when an exception is caught.

once above class has defined, exception can be rise as following,

Raising an Exceptions:

Python Exceptions can be raised in several ways by using the raise statement.

Syntax for the raise statement,

Python Exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is explained in the following example,

Example1:
#raising exception

def function1( valuel ):
   if valuel < 1:
      raise "Invalid valuel", valuel
      #The code below to this would not be executed
      #if we raise the exception

To catch an exception, an “except” clause must refer to the same exception thrown either class object or simple string. 

Example2:
try:
   Business Logic here...
except "Invalid valuel!":
   Exception handling here...
else:
   Rest of the code here...

Argument of an Exception:

Python Exception can have an Argument, a value that gives additional information about the problem. The contents of the argument vary by exception. An exception’s argument can be captured by supplying a variable in the except clause as given in the below box,

#Defining a function here.

def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain number\n", Argument

#Call above function here.