Showing posts with label FileNotFoundError. Show all posts
Showing posts with label FileNotFoundError. Show all posts

Mar 18, 2013

Python User Defined Exceptions


Today we discuss about raising exceptions manually (Python User Defined Exceptions).

1) We already know we have built in exceptions in Python like ValueError, IOError, FileNotFoundError, ZeroDivisionError

2) But sometimes we might have to write custom exceptions on our own to catch few scenarios.

Lets discuss how to implement user defined exception with an example.

In the below example :

nonEmptyValException                                  #User Defined Exception

ValueError, ZeroDivisionError, EOFError   #Built-in Exceptions


exceptions_raise_manual.py
import sys

class nonEmptyValException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, num):
        Exception.__init__(self)
        self.num = num
      
try:
    a = int(input('Enter some integer for Dividend --> '))
    b = int(input('Enter some integer for Divisor --> '))
    
    if not a:
       raise nonEmptyValException(a)
       
    if not b:
       raise nonEmptyValException(b)
    
    c = a/b;    

    print ("Final Value is : ", c) 
    
except  ValueError:
    print('ValueError: Please enter only Integer Value')   
except ZeroDivisionError:
    print('ZeroDivisionError: The input divisor is %d, was expecting a Non-Zero number' % (b))   
except EOFError:
    print('\nWhy did you do an EOF on me?')
except nonEmptyValException as error:
    print('nonEmptyValException: The input is %d, was expecting a integer number' % (error.num))  


Please refer to other Python Exceptions Concepts :
All Python Exceptions Related Topics
Exceptions in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton



Mar 12, 2013

Exceptions in Python

Today, we discuss about the following :
1) Try block in Python
2) finally block
3) Exceptions

-> In the following example, we can catch exceptions occurred in the code.

-> Keep the code in try block, when an exception is there, it is being caught by except

-> Finally block will be called at the last after the end of execution of the block.

-> In this example, there are few well know exceptions like FileNotFoundError, IOError, EOFError, ValueError


read.txt (Input File)

Abraham Lincoln
Mother Teresa
Paul Coelho

exceptions_test.py
  
import time
import sys

try:    
    f = open('read.txt', 'r') 
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(0.5)  #1/2 sec
        print(line)
except FileNotFoundError:
    print('\n File NOT Found Error')
    sys.exit
except IOError:
    print('\n IO Error')
    sys.exit
except EOFError:
    print('\nWhy did you do an EOF on me?')
    sys.exit
except ValueError:
    print("\nValue Error.")
    sys.exit
finally:
    f.close()
    print('Cleaning up...closed the file')
                                                    
                                           


You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python