Python for Bioinformatics

This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics

Chapter 7: Error Handling


In [ ]:
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples


  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 16.5M  100 16.5M    0     0  14.3M      0  0:00:01  0:00:01 --:--:-- 14.3M
mkdir: cannot create directory 'samples': File exists
BLAST_output.xml
TAIR7_Transcripts_by_map_position.gz
pMOSBlue.txt
fishbacteria.csv
UniVec_Core.nsq
t3beta.fasta
PythonU.db
input4align.dnd
pdb1apk.ent.gz
readme.txt
contig1.ace
example.aln
hsc1.fasta
bioinfo/seqs/15721870.fasta
primers.txt
bioinfo/seqs/4586830.fasta
bioinfo/seqs/7638455.fasta
GSM188012.CEL
3seqs.fas
sampleX.fas
sampleXblast.xml
B1.csv
phd1
conglycinin.phy
bioinfo/seqs/218744616.fasta
spfile.txt
bioinfo/seqs/513419.fasta
bioinfo/seqs/513710.fasta
prot.fas
cas9align.fasta
seqA.fas
bioinfo/seqs/
bioinfo/
pdbaa
other.xml
vectorssmall.fasta
t3.fasta
a19.gp
data.csv
input4align.fasta
B1IXL9.txt
fasta22.fas
bioinfo/seqs/7415878.fasta
bioinfo/seqs/513718.fasta
bioinfo/seqs/513719.fasta
bioinfo/seqs/6598312.fasta
UniVec_Core.nin
Q5R5X8.fas
bioinfo/seqs/513717.fasta
BcrA.gp
bioinfo/seqs/2623545.fasta
bioinfo/seqs/63108399.fasta
conglycinin.dnd
NC2033.txt
fishdata.csv
uniprotrecord.xml
BLAST_output.html
Q9JJE1.xml
test3.csv
UniVec_Core.nhr
sampledata.xlsx
UniVec_Core
NC_006581.gb
conglycinin.multiple.phy
conglycinin.fasta

Listing 7.1: wotest.py: Program with no error checking


In [ ]:
with open('myfile.csv') as fh:
    line = fh.readline()
value = line.split('\t')[0]
with open('other.txt',"w") as fw:
    fw.write(str(int(value)*.2))


---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-2-a64eb4cb1322> in <module>()
----> 1 with open('myfile.csv') as fh:
      2     line = fh.readline()
      3 value = line.split('\t')[0]
      4 with open('other.txt',"w") as fw:
      5     fw.write(str(int(value)*.2))

FileNotFoundError: [Errno 2] No such file or directory: 'myfile.csv'

Listing 7.2: LBYL.py: Error handling LBYL version


In [ ]:
import os
iname = input("Enter input filename: ")
oname = input("Enter output filename: ")
if os.path.exists(iname):
    with open(iname) as fh:
        line = fh.readline()
    if "\t" in line:
        value = line.split('\t')[0]
        if os.access(oname, os.W_OK) == 0:
            with open(oname, 'w') as fw:
                if value.isdigit():
                    fw.write(str(int(value)*.2))
                else:
                    print("Can’t be converted to int")
        else:
            print("Output file is not writable")
    else:
        print("There is no TAB. Check the input file")
else:
    print("The file doesn’t exist")


Enter input filename: hola
Enter output filename: hello
The file doesn’t exist

Listing 7.3: exception.py: Similar to 7.2 but with exception handling.


In [ ]:
try:
    iname = input("Enter input filename: ")
    oname = input("Enter output filename: ")
    with open(iname) as fh:
        line = fh.readline()
    if '\t' in line:
        value = line.split('\t')[0]
    with open(oname, 'w') as fw:
        fw.write(str(int(value)*.2))
except NameError:
    print("There is no TAB. Check the input file")
except FileNotFoundError:
    print("File not exist")
except PermissionError:
    print("Can’t write to outfile.")
except ValueError:
    print("The value can’t be converted to int")
else:
    print("Thank you!. Everything went OK.")


Enter input filename: hola
Enter output filename: hello
File not exist

Listing 7.4: nested.py: Code with nested exceptions


In [ ]:
iname = input("Enter input filename: ")
oname = input("Enter output filename: ")
try:
    with open(iname) as fh:
        line = fh.readline()
except FileNotFoundError:
    print("File not exist")
if '\t' in line:
    value = line.split('\t')[0]
try:
    with open(oname, 'w') as fw:
        fw.write(str(int(value)*.2))
except NameError:
    print("There is no TAB. Check the input file")
except PermissionError:
    print("Can’t write to outfile.")
except ValueError:
    print("The value can’t be converted to int")
else:
    print("Thank you!. Everything went OK.")


Enter input filename: hola
Enter output filename: hello
File not exist
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-053b34386a3d> in <module>()
      6 except FileNotFoundError:
      7     print("File not exist")
----> 8 if '\t' in line:
      9     value = line.split('\t')[0]
     10 try:

NameError: name 'line' is not defined

In [ ]:
d = {"A":"Adenine","C":"Cytosine","T":"Timine","G":"Guanine"}
try:
    print(d[input("Enter letter: ")])
except:
    print("No such nucleotide")


Enter letter: L
No such nucleotide

In [ ]:
d = {"A":"Adenine", "C":"Cytosine", "T":"Timine", "G":"Guanine"}
try:
    print(d[input("Enter letter: ")])
except EOFError:
    print("Good bye!")
except KeyError:
    print("No such nucleotide")


Enter letter: A
Adenine

Listing 7.5: sysexc.py: Using sys.exc_info()


In [ ]:
import sys

try:
    0/0
except:
    a,b,c = sys.exc_info()
    print('Error name: {0}'.format(a.__name__))
    print('Message: {0}'.format(b))
    print('Error in line: {}'.format(c.tb_lineno))


Error name: ZeroDivisionError
Message: division by zero
Error in line: 4

Listing 7.6: sysexc2.py: Another use of sys.exc_info()


In [ ]:
import sys

try:
    x = open('random_filename')
except:
    a, b = sys.exc_info()[:2]
    print('Error name: {}'.format(a.__name__))
    print('Error code: {}'.format(b.args[0]))
    print('Error message: {}'.format(b.args[1]))


Error name: FileNotFoundError
Error code: 2
Error message: No such file or directory

In [ ]:
def avg(numbers):
    return sum(numbers)/len(numbers)

In [ ]:
avg([])


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-10-96c1bb829360> in <module>()
----> 1 avg([])

<ipython-input-9-3a13d6961f52> in avg(numbers)
      1 def avg(numbers):
----> 2     return sum(numbers)/len(numbers)

ZeroDivisionError: division by zero

In [ ]:
def avg(numbers):
    if not numbers:
        raise ValueError("Please enter at least one element")
    return sum(numbers)/len(numbers)

In [ ]:
avg([])


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-96c1bb829360> in <module>()
----> 1 avg([])

<ipython-input-11-ed4c8cf5cbc0> in avg(numbers)
      1 def avg(numbers):
      2     if not numbers:
----> 3         raise ValueError("Please enter at least one element")
      4     return sum(numbers)/len(numbers)

ValueError: Please enter at least one element