Python Tutorials

Overview

  • The try block lets you test a block of code for errors
  • The except block lets you handle the error
  • The else block lets you execute code when there is no error
  • The finally block lets you execute code, regardless of the result of the try block and except block

Using Try and Accept

When an error (exception) occurs, Python will normally stop and generate an error message.

However, these exceptions can be handled using the try statement.

try:
    print(x) #an error will occur because x is not defined
except:
    print("An exception occurred")

Output:

An exception occurred

Throwing Multiple Exceptions

The following will print one message if the try block raises a NameError, and another message for other errors.

try:
    print(x) #an error will occur because x is not defined
except NameError:
    print("x is not defined")
except:
    print("An exception occured")

Output:

x is not defined

Using the else Keyword

The else keyword can be used to define a block of code to be executed if no errors are raised.

try:
    print("Hello World")
except:
    print("There was an exception")
else:
    print("There were no exceptions")

Output:

Hello World
There were no exceptions

Using the finally Keyword

The finally keyword, if specified, will execute a block regardless if the try block raises an error or not.

try:
    print(x)
except:
    print("There was an exception")
finally:
    print("The code has finished running")

Output:

There was an exception
The code has finished running

The finally block can be useful to close objects and clean up resources.

try:
    f = open("file.txt")
    try:
        f.write("Hello World")
    except:
        print("Something went wrong writing to the file")
    finally:
        f.close()
except:
      print("Something went wrong opening the file") 

Output:

Something went wrong writing to the file

Intentionally Raising an Exception

As a Python developer, there may be times when you want to intentionally throw an exception. In these cases, the raise keyword is used.

x = -1

if x < 0:
    raise Exception("Sorry, numbers below zero are not allowed")

Output:

Traceback (most recent call last):
  File "./prog.py", line 4, in <module>
Exception: Sorry, numbers below zero are not allowed

The type of error can also be defined and printed.

x = "hello world"

if not type(x) is int:
    raise TypeError("Only integers are allowed")

Output:

Traceback (most recent call last):
  File "demo_ref_keyword_raise2.py", line 4, in <module>
    raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string
  • Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
  • Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), unindexed (items cannot be referred to by index or key), and duplicates are NOT ALLOWED
  • As of v3.7, Python dictionaries are ordered and duplicates ARE ALLOWED; in v3.6 and earlier, dictionaries were unordered (did not have a defined order and could not be referred to using an index)
  • Python does not have built-in support for arrays, but Python lists can be used as pseudo “arrays”; therefore, all Python list methods will work with these pseudo “arrays”

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.