Exception Handling in python














































Exception Handling in python



Exception Handling


Exception:
An exception is an error that happens during execution of program. When that error occurs, python generate an exception that can be handled, which avoids your program to crash.

Why we use Exceptions:
To maintain the normal flow of the application.

Some example exceptions(errors):
    
IOError:
If the file cannot be opened.

KeyboardInterrupt:

Raises when the user hits the interrupt key.

ValueError:

Raises when a built- in operation or function receives an argument that has the right type but an inappropriate value.

ZeroDivisionError:

Raises when division or modulo by zero takes place for all numeric types.

NameError:

Raises when an identifier is not found in the local or global namespace.

TypeError

Raises when an operation or function is attempted that is invalid for the specified data type.


Handling Exceptions:

We can handle exceptions in our program by using try block and except block.  A critical operation which can raise exception is placed inside the try block and the code that handles exception is written in except
block.  The syntax for try-except block can be given as,

Syntax:

try:

      Perform operations here;

      .......................

except Exception:

      If there is Exception1, execute this block.

EXAMPLE:


num=int(input("Enter the numerator:"))
deno=int(input("Enter the denominator:"))
try:
quo=num/deno
print("QUOTIENT:",quo)
except ZeroDivisionError:
print("Denominator cannot be zero")

OUTPUT:

Note:

  1. A single try statement can have multiple except statements.  This is useful when the try block contains statements that may throw different types of exceptions.

  2. After the except clause(s), you can include an else-clause.  The code in the else-block executes if the code in the try block does not raise an exception. 


Try Block with multiple except statements:


try:

          Perform operations here

          ..................

except Exception1:

          If there is Exception1, then execute this block

except Exception2:

          If there is Exception2, then execute this block

          ...................

EXAMPLE:

try:
num=int(input('enter the number:'))
print(num**2)
except KeyboardInterrupt:
print('Interrupt occured')
except ValueError:
print('check the number you have entered')


OUTPUT:

The else clause:

The try... except block can optionally have an else clause, which, when present, must follow all except blocks.  The statement in the else block is executed only if the try clause does not raise an exception.

Syntax:

try:

   Perform operations here

   ...................

except:

    If there is any exception, then execute this block.

    ..................

else:

    If there is no exception then execute this block.


EXAMPLE

try:
file=open('File1.txt')
str=file.readline()
print(str)
except IOError:
print
("Error occurred during Input .......Program Terminating.......")
else:
print("Program Terminating Successfully")

OUTPUT:

Hello
Program Terminating Successfully


except block without exception name:

You can even specify an except block without mentioning any exception (i.e., except:).  This type of except block if present should be at the end of the try-except block.

try:

   You do your operations here

   ....................

except exception1:

   If there is any exception, then execute this block.

   ....................

except:

   If there is any exception, then execute this block.

   ....................

              This kind of  a try-except statement catches all the exceptions that occur.  Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

EXAMPLE:

try:
file=open('File1.txt')
str=f.readline()
print(str)
except IOError:
print("Error occurred during Input ......Program Terminating......")
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error....Program Terminating.....")

OUTPUT:

Unexpected error...Program Terminating...


The except Clause with Multiple Exceptions:

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


try:

   Perform 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 exception:

We can  raise an exception using the raise keyword.  The general syntax for the raise statement is,

 raise Exception-Name

EXAMPLE:

try:
num=10
print(num)
raise ValueError
except:
print("exception occured.. Program Terminating..")

OUTPUT:

10
exception occured.. Program Terminating..


The try-finally clause:

We can use a finally 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

Syntax:

try:

   Perform operations here;

   ..................

   Due to any exception, this may be skipped.

finally:

   This would always be executed.

   ....................

EXAMPLE:

try:
print('raising exception')
raise ValueError
finally:
print("Performing clean up in finally..")


OUTPUT:



Comments