Python Forum
Exception not thrown in python3
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Exception not thrown in python3
#1
Why does the call of inclusive_range() at line 71 not throw an exception and instead it prints "Test FAILED"?

def test(*args):
    print(type(args))
    print(len(args))
    if len(args) == 1:
        raise ValueError("too many args, [1, 2]")

def inclusive_range(*args):
    numargs = len(args)
    print(numargs)
    if numargs < 1:
        raise ValueError("number of args less than 1, needed interval [1, 3]")
    elif numargs == 1:
        start = 0
        stop = args[0]
        step = 1
    elif numargs == 2:
        (start, stop) = args
        step = 1
    elif numargs == 3:
        (start, stop, step) = args
    else:
        raise ValueError("number of args greater than 3, needed interval [1, 3]")
    i = start
    while i <= stop:
        yield i
        i += step

# test cases
def main():
    # valid 1 arg
    for i in inclusive_range(20):
        print(i, end=' ')
    print()
        
    # valid 2 args
    for i in inclusive_range(0, 21):
        print(i, end=' ')
    print()
    
    # valid 3 args
    for i in inclusive_range(0, 22, 2):
        print(i, end=' ')
    print()
    
    # invalid 0 args
    try:
        myRange = inclusive_range()
        for i in myRange:
            print(i)
    except ValueError as e:
        print(e)
    except:
        print("Unknown exception occured")
    else:
        print("Test FAILED")
        
    # invalid 4 args
    try:
        myRange = inclusive_range(1, 2, 3, 4)
        for i in myRange:
            print(i)
    except ValueError as e:
        print(e)
    except:
        print("Unknown exception occured")
    else:
        print("Test FAILED")
        
    # invalid 5 args, warning myRange not used (possibly optimized out by python)
    try:
        myRange = inclusive_range(1, 2, 3, 4, 5)
    except ValueError as e:
        print(e)
    except:
        print("Unknown exception occured")
    else:
        print("Test FAILED")
    
    test()
    try:
        test(1)
    except ValueError as e:
        print(e)
    else:
        print("everything is fine here, move along.")


if __name__ == "__main__": main()
Reply
#2
Else block will be executed no matter what. Or it was finally?!...

Well, the else block will be executed if there was no exception.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
surround your code with:
try:
    ...
except Exception as ex:
    # todo -- Use tkinter.messagebox here
    template = "An exception of type {0} occurred. arguments: \n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print(message)
    raise Exception
to see what's being thrown
Reply
#4
I am now learning python3. From what I remember it was finally that was always executed.
I have made two different versions of the same function.
1st version is generator function
2nd version is generator object

See both versions here:
https://gist.github.com/ONEoo7
Reply
#5
Finally will be executed in all circumstances. Else will be executed before finally  if there is no exception in the try block.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
There was no exception, so else block was executed. Your inclusive_range is not a standard function, but generator function and call of inclusive_range() does not execute any code from inclusive_range, only returns generator object (iterator). You need to use next() on it (or directly call .__next__() ) to execute code from its body.
Reply
#7
Ok, so just calling the function does not actually make it behave like a normal c/c++ function or method. It returns immediately with a generator object(seen with the debugger). When used in a for loop or manually calling .__next__() on the returned generator object will actually call the function and behave as expected, throw the exception in this case.

Thank you @zivoni.
Reply
#8
(Apr-08-2017, 09:45 PM)ONEoo7 Wrote: When used in a for loop or manually calling .__next__() on the returned generator object will actually call the function and behave as expected, throw the exception in this case.
Yes,and a generator run to StopIteration so that what you catch.
Eg:
def yrange(n):
    i = 0
    while i < n:
        yield i
        i += 1

>>> n = yrange(3)
>>> n
<generator object yrange at 0x02A4C3A0>
>>> next(n)
0
>>> next(n)
1
>>> next(n)
2
>>> next(n)
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
StopIteration
A lot more build in stuff like range, map, zip, filter... ect has become generator/iterables in Python 3.x.
This conserve space rather than producing a result list all at once in memory.

It's a powerful concept as a example can slice in and take out the only part that needed.
>>> from itertools import islice
>>> g = (i for i in range(100))
>>> g
<generator object <genexpr> at 0x0124E4B8>
>>> list(islice(g, 50, 55))
[50, 51, 52, 53, 54]
So here get only Fibonacci from 35 to 40 executed.
from itertools import islice

def fib_gen():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b 

>>> list(islice(fib_gen(), 35, 40))
[14930352, 24157817, 39088169, 63245986, 102334155]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  which exception should be thrown for a sequence of the wrong length? Skaperen 1 851 Jan-06-2023, 04:13 AM
Last Post: deanhystad
  Pytest API Post call thrown errors pyseeker 4 3,645 Dec-08-2019, 04:53 PM
Last Post: pyseeker
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,925 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE
  Invalid argument error thrown. pyseeker 4 8,624 Sep-10-2019, 07:03 PM
Last Post: pyseeker
  During handling of the above exception, another exception occurred Skaperen 7 26,918 Dec-21-2018, 10:58 AM
Last Post: Gribouillis
  pytest fixture in conftest.py thrown error while in the test file runs OzzieOzzum 1 3,985 Jul-31-2018, 12:12 PM
Last Post: OzzieOzzum
  [split] Teacher (thrown in at the deep end - help) Mr90 2 3,021 May-23-2018, 02:04 PM
Last Post: DeaD_EyE
  Teacher (thrown in at the deep end - help) Mr90 5 3,897 May-22-2018, 01:08 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020