Linux

Python Exception

When Python interpreter encounter error. It stops the running program and shows an error message detailing the exception.
Very simple example
Python exception exception
Exception example
Using Python's exception handling functionality, you can intercept and handle exception so that your program does not end abruptly. At the very least. You can have your program exit gracefully instead of crashing awkwardly.

Try statement with an except clause

In order to handle the exception, try and except block is used. A single try statement can have multiple except statement. Due to multiple Python exception, program can throw a exception in appropriate section.
try:
   num = float(raw_input("Enter a number "))
except:
   print "Some thing went wrong"
Out-put
Python error handing example
handling the error
Call to float() raises an exception, the exception is caught and the crafted message is displayed "Some thing went wrong". If no exception is raised, num gets the number entered by user and the program skips the except clause, continuing with the rest of the code.
Now we take a look on syntax of try and except block.
	try:
   		operation block;
  
	except Exception_name:
		If there is Exception_name1 then execute this block.
	except Exception_name2:
 		If there is Exception_name2, then execute this block.
 	 
	else:
		If there is no exception then execute this block.

Multiple Python exception block

Let us discuss our first example
try:
   num = int(raw_input("Enter the number "))
   re = 100/num
except: ValueError :
   print "Value is not int type"
except: ZeroDivisionError :
   print "Don't use zero"
else: :
   print "result is ",re
Let us check the out-put with code
Python Multiple exception handling
Multiple exception
In above example you can understand that the error throws in particular exception block.

except clause with no Python exceptions:

Consider if you don't know the particular Python exception type. You can use just except block.
Let us discuss next example
try:
   num = int(raw_input("Enter the number "))
   re = 100/num
except:
   print "Something is wrong"
else:
   print "result is ",re
Out-put
exception handle by single except
Single exception Block
You can see both previous exceptions fall in same block. However from error you can not determine which type of error occurred.

Handling multiple Python exception type

One single exception block can handle multiple exception types.
Syntax
except ( Exception1, Exception2) :
try:
   num = int(raw_input("Enter the number "))
   re = 100/num
except (ValueError, ZeroDivisionError) :
   print "Something is wrong"
else:
   print "result is ",re
Out-put
Python handling multiple exception type
Handling multiple exception type
You can see that one exception block is handling two type of exceptions.

Python The try/finally Statement

When you are completely sure that an action must be happened after code run, regardless of the exception behaviour of the program.
try:
	  #run this action first
except: 
	 # Run if exception occurs 
Finally :
	   #Always run this code
The order of statement should be in order.
try -> except -> else -> finally
Let us discuss our first example
try:
   num = int(raw_input("Enter the number "))
   re = 100/num
except:
   print "Something is wrong"
else:
   print "result is ",re
finally :
   print "finally program ends"
Out-put
Python try finally in exception
try/finally
The finally-block is executed once the try-block is complete and any raised exceptions have been handled. Infect finally block will run even if new exception is raised.
Let us check in example
try:
   num = int(raw_input("Enter the number "))
   re = 100/num
except ZeroDivisionError :
   print "Something is wrong"
else:
   print "result is ",re
finally :
   print "finally ends"
Let us discuss the out-put with pictorial diagram.
Python finally statement run even exception is not handled
finally run even exception is not handled
From out-put you can understand that try block will run whether error is handled or not.

Program find its exception type

try:
   num = int(raw_input("Enter the number "))
   re = 100/num
except Exception as e
   print "Exception: ", type(e)
The above code presented a beautiful technique to find its exception type. The above code catches the exception as e and type(e) displays its exception type.
Python exception catches its exception type
Python exception catches its exception type
From the output you can see code itself telling the exception type.

Raising an Python exceptions:

To trigger exceptions explicitly, you can code raise statements. Their general form is simple Syntax
raise <instance> # Raise instance of class
raise <class> # Make and raise instance of class
raise # Reraise the most recent exception
Consider a very simple example
val = int(raw_input("Enter the number "))
try:
   if val ==2:
      raise IOError
except IOError:
   print "an exception is raised"
else:
   print "value is not 2"
If you enter value equal to 2 then if block will raise the exception by using raise keyword. The except block will handle that exception.
Lets discuss the example with pictorial diagram.
Python Exception raised and caught
Exception raised
In above example, very simple example just to demonstrate how to raise the exception, if val == 2 then exception IOError is raised. (2 may be unlucky number for user ) . And this exception is caught by except block .
If you type raise in python shell then
Python exception raised by raised keyword
Exception raised

User-Defined Exceptions

Python also allows you to create your own exceptions by creating a new exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly.
For example:
class MyError(Exception):
   def __init__(self, value):
      self.value = value
   def __str__(self):
      return repr(self.value)
try:
   raise MyError("ohh")
except MyError :
   print "My exception occurred"
Out-put
User defined error exception
User-Defined MyError exception
In above example, A subclass MyError is made by deriving class from the standard built-in exceptions. In this example, the default __init__() of Exception has been overridden. The new behaviour simply creates the value attribute. This replaces the default behaviour of creating the args attribute. In try: block exception is raised explicitly by using raise keyword. The Exception is caught by except block.
Consider except block do not able to caught exception see example below
classMyError(Exception):
   def __init__(self, value):
      self.value = value
   def __str__(self):
      return repr(self.value)
try:
   raise MyError("ohh")
except IOError :
   print "My exception occurred"
Out-put
User defined error exception
User-Defined MyError exception
In above program the except block contains different exception type. That's why program could not handle the user defined exception.
To study the Built-in Python exceptions you can study the official page of Python docs.




admin