Python Forum

Full Version: create my exception to my function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I have a function that read data after a I split the message , and sometime I get wrong message-- which lead to wrong data input
I want to add to it exception , so in the main code I will see this problem and do what I want to do with this information

def splitingData(msg):
    data = msg.split('!')
    lng = len(data)
    i = 0
    for d in data:
        print(str(i) + ' : ' + d)
        i += 1
    if lng < 10:
        raise Exception('Missing data!')  ----> is this correct? 
    else:
        pass

main():
    try:
        splitingData(MyTestData)
    exception (what I need to do here?
Try this for example
# normal function don't print anything
# when they do, take a name that indicates this.
def print_split_data(msg):
    data = msg.split('!')
    lng = len(data)
    i = 0
    for d in data:
        print(str(i) + ' : ' + d)
        i += 1
    if lng < 10:
        raise ValueError('Missing data in message')

def main():
    test_data = 'spam!eggs!ham!ham'
    try:
        print_split_data(test_data)
    except ValueError:
        print('Well the call to print_split_data() failed')

if __name__ == '__main__':
    main()
Output:
0 : spam 1 : eggs 2 : ham 3 : ham Well the call to print_split_data() failed
Ok
this is also good for me

Thanks!