Search code examples
pythontry-catchexcept

try: / except: pass not continuing onto rest of script?


This is part of my script:

try:    
    read2length = len(reads[1])
    x2 = data[read1length:read1length+read2length,0]
    y2 = data[read1length:read1length+read2length,1]
    fig = plt.figure()
    plt.bar(x2,y2, align='center')
    fig.suptitle('Read 2 Camera Timeouts', fontsize=20)
    plt.xlabel('Cycle', fontsize=18)
    plt.ylabel('#', fontsize=16)
    if read2length < 50:
        plt.xticks(x1, fontsize=14)
    fig.savefig(join((path),'Read 2 Camera Timeouts.jpg'))
except: pass 
try:
    read3length = len(reads[2])
    x3 = data[read1length+read2length:read1length+read2length+read3length,0]
    y3 = data[read1length+read2length:read1length+read2length+read3length,1]
    fig = plt.figure()    
    plt.bar(x3,y3, align='center')
    fig.suptitle('Read 3 Camera Timeouts', fontsize=20)
    plt.xlabel('Cycle', fontsize=18)
    plt.ylabel('#', fontsize=16)
    if read3length < 50:
        plt.xticks(x1, fontsize=14)
    fig.savefig(join((path),'Read 3 Camera Timeouts.jpg'))
except: pass          

I want the script to try the first one and the second one. whether they work or not i want the script to continue.

I keep getting read2length is not defined?

Whats going on?


Solution

  • If the expression len(reads[1]) throws an exception (say, IndexError) then the name read2length is never assigned to.

    This then leads to an exception if your next try block tries to use that name anyway.

    You should really not use pokemon exception handling (you don't want to catch them all, really). Keep your exception handling as close to the exception-throwing code as possible, and only handle specific exceptions.

    For example, if you want to handle reads[1] throwing an index error, then handle just that exception:

    try:
        read2length = len(reads[1])
    except IndexError:
        # not enough elements here; assume 0
        read2length = 0
    else:
        x2 = data[read1length:read1length+read2length,0]
        y2 = data[read1length:read1length+read2length,1]
        fig = plt.figure()
        plt.bar(x2,y2, align='center')
        fig.suptitle('Read 2 Camera Timeouts', fontsize=20)
        plt.xlabel('Cycle', fontsize=18)
        plt.ylabel('#', fontsize=16)
        if read2length < 50:
            plt.xticks(x1, fontsize=14)
        fig.savefig(join((path),'Read 2 Camera Timeouts.jpg'))
    

    Now read2length is bound to an integer, always.