Tutorial #7: Python Error Handling Best Practices

Python Error Handling Best Practices Professional!

Complete Python Bootcamp From Zero to Hero in Python (Error Handling)

Contents

See full code here

1. Errors and Exception Handling

1.1 try and except and else

1.2 try and except and finally

2. Unit testing

2.1 Pylint

2.2 Using unittest library

browse

1.1 try and except and else

def my_func(n):

result = n + 2

return result

try:

my_func(2)

except:

print(‘Not Added Correctly!’)

else:

print(‘Added Correctly!’)

print(my_func(2))

# note: Try to input myfunc(‘a’) and see what happens

—————————————————————–

try:

f = open(‘testfile.txt’, ‘w’)

f.write(‘Test write this’)

except IOError:

# This will only check for an IOError exception and then execute this print statement

print(“Error: Could not find file or read data”)

else:

print(“Content written successfully”)

f.close()

# output: Content written successfully

# note: to create testfile.txt and write inside

—————————————————————–

try:

# to create testfile.txt and write inside

f = open(‘testfile.123’, ‘r’)

f.write(‘Test write this’)

except IOError:

# This will only check for an IOError exception and then execute this print statement

print(“Error: Could not find file or read data”)

else:

print(“Content written successfully”)

f.close()

# output: Error: Could not find file or read data

# note: because no available file to read

—————————————————————–

1.2 try and except and finally

try:

f = open(“testfile”, “w”)

f.write(“Test write statement”)

f.close()

finally:

print(“Always execute finally code blocks”)

—————————————————————–

try:

# to create testfile.txt and write inside

f = open(‘testfile’, ‘w’)

f.write(‘Test write this 3’)

except:

# This will only check for an IOError exception and then execute this print statement

print(“Error: Could not find file or read data”)

finally:

print(“Content written successfully”)

—————————————————————–

def ask_int():

try:

val = int(input(“Please enter an integer: “))

except:

print(“Looks like you did not enter an integer!”)

val = int(input(“Try again-Please enter an integer: “))

finally:

print(“Finally, I executed!”)

print(val)

ask_int()

—————————————————————–

def ask_int():

while True:

try:

val = int(input(“Please enter an integer: “))

except:

print(“Looks like you did not enter an integer!”)

continue

else:

print(“Yep that’s an integer!”)

break

finally:

print(“Finally, I executed!”)

print(val)

ask_int()

—————————————————————–

2 Unit Testing

It is important as writing good code is writing good tests. Better to find bugs yourself than have them reported to you!

For now what we have is pep8 and pylint

2.1 Pylint

Static Code Checker and Code Analysis

install pylint using anaconda

create ‘simple1.py’ then add this:

“””

A very simple script.

“””

def myfunc():

“””

An extremely simple function.

“””

first = 1

second = 2

print(first)

print(second)

myfunc()

—-

Go to terminal then type: ‘pylint simple1.py’ then see the result

Check files here

—————————————————————–

create ‘simple2.py’ then add this:

“””

A very simple script.

“””

def myfunc():

“””

An extremely simple function.

“””

first = 1

second = 2

print(first)

print(‘second’)

myfunc()

—-

Go to terminal then type: ‘pylint simple2.py’ then see the result

Check files here

—————————————————————–

2.2 Using unittest library

Create cap.py then add this:

import string

def cap_word(text):

return string.capwords(text) # Capitalize each word

def cap_first_word(text):

return text.capitalize() # Capitalize first word in sentence

—————————————————————–

Create cap_test.py then add this:

import unittest

import cap

class TestCap(unittest.TestCase):

def test_one_word(self):

text = ‘python’

result = cap.cap_word(text)

self.assertEqual(result, ‘Python’)

def test_multiple_words(self):

text = ‘monty python’

result = cap.cap_word(text)

self.assertEqual(result, ‘Monty Python’)

def test_with_apostrophes(self):

text = str(“monty python’s flying circus”)

result = cap.cap_word(text)

self.assertEqual(result, “Monty Python’s Flying Circus”)

if __name__ == ‘__main__’:

unittest.main()

Then run your cap_test.py and see result

Make this the year that you took a risk, you learned highly in demand skills, you had new experiences, and you received new opportunities. I hope you join me in this journey.

Python Error Handling Best Practices – Studies Show!

This is the proudest work I have ever done in my life and I am confident that you won’t find a course better than this.

There is so much information out there, so many opinions, and so many ways of doing things, that unless you have spent the last few years working with these technologies in a company, you will never fully understand. So this course is the answer to that exact problem for you: How to gain experience when you need experience to get hired? I have gone through thousands of coding books, online tutorials and bootcamps. Throughout the years I have taken notes on what has worked and what hasn’t, and I have created this course to narrow down the most efficient way to learn with the most relevant information.

Python Error Handling Best Practices – Brainy Secrets!

Python Error Handling Best Practices
Tagged : / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /