Manually raising exception in Python

Sometime you may need to manually raise exception in Python programming instead of thrown automatically. For manually raising exception, you can use the raise statement. Here is an example of using raise.

try:
    f = open('samples/myfile.txt')
    s = f.readline()
    f.close()

    if len(s) > 0:
        i = int(s.strip())
    else:
        raise ValueError("Manual exception - the file does not have any data.")
    
except (OSError, ValueError) as err:
    print("\nError: {0}".format(err) , "\n")
except Exception as err:
    print("\nSome Other Error: {0}".format(err), "\n")
Manually raising exception in Python

See my other article on catching multiple exceptions in an except clause.

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.