user1816377
user1816377

Reputation: 245

How do I return an exception?

I wrote a function that needs to do 3 checks and if one of the tests fails it should return an exception of type of LookupError, but it doesn't work. (*verify_checksum is another function)

def check_datagram(datagram, src_comp, dst_app):
    try:
        src_comp==datagram[0:16]
    except LookupError:
        return "Mismatch in src_comp"
    try:
        dst_app==datagram[40:48]
    except LookupError:
        return "Mismatch in dst_app"
    try:
        verify_checksum(datagram)
    except False:
        return "Wrong checksum"
    return True

For example:

Input:

check_datagram("1111000000001111000011111111000001010101101010101111111111111111000000001111111100000000","0000111100001111", "11110000")

Expected output:

"Mismatch in dst_app"

Upvotes: 0

Views: 1888

Answers (2)

Aleksandr Zonov
Aleksandr Zonov

Reputation: 185

With construction from NPE's answer you should use try..except there where you'll use declared check_datagram() function.

#python3
try:
    check_datagram(a,b,c)
except LookupError as e:
    print(str(e))

That allow you to get message from raised error.

Upvotes: 0

NPE
NPE

Reputation: 500257

def check_datagram(datagram, src_comp, dst_app):
    if src_comp != datagram[0:16]:
        raise LookupError("Mismatch in src_comp")
    if dst_app != datagram[40:48]:
        raise LookupError("Mismatch in dst_app")
    if not verify_checksum(datagram):
        raise LookupError("Wrong checksum")
    return True # redundant?

Upvotes: 3

Related Questions