Manually raising exception in Python

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.

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

    if len(s) > 0:
        i = int(s.strip())
        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.


Related Articles & Tools

Leave your thoughts...

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