Tuesday, October 8, 2013

Second Post 9/30 Raise and Exception

9/30 Raise and Exception
In last week, I learned how to raise errors for different situations with exceptions which is very interesting and helpful.
There are some errors that appear frequently before when I running my codes.
For example:
name error,

>>>hello
NameError: name "hello" is not defined

syntax error,

def function()
SyntaxError: invalid syntax

index error,

>>>list = [1, 2, 3]
>>>list[4]
IndexError: list index out of range

input error,
>>>f = open("x.txt","r")
IOError: No such file or directory: "x.txt"

......

After lectures of this week, I can raise my own designed error base on the situation.
Keywords are: raise, try, except


1.
def raiser(x):
    if x == "So sue me!":
        raise E2Exception("New Yorker")

When the input x is exactly the same as "So sue me!" it raise an exception named E2Exception which is a subclass of Exception(I will mention subclass later in this post).


from e2a import raiser, E2Exception, E2OddException


2.
def reporter(raiser, x):
    try:
        raiser(x)
    except ValueError as v:
        return "Value"




No comments:

Post a Comment