4️⃣

19.4 Else & Assert

Else & Assert

Else Clause

The else clause in exception handling is used when you want code to run if there were no errors raised under the try clause. This could be helpful if you ever wanted confirmation that there were no exceptions raised or if there is code you want to run only if there are no errors. The else clause should be placed after the except clauses.

Example:

try:
    x = "hello world"
    print(x)
except FileNotFoundError:
    print('uh oh, file not found')
except TypeError:
    print('uh oh, type error')
else: #will run because there are no errors
    print('everything good here!')

View code on GitHub.

Output:

hello world
everything good here!

Assert Keyword

The assert keyword is used in Python mainly for debugging. It throws an AssertionError if a certain condition is not met. assert can also take in an optional custom error message, which can help explain why an exception was raise. assert <condition>, <error message> is the format for using the assert keyword.

Example:

string = "goodbye"
assert string == "hello", "string is not hello"
print(string) #this will not be run because assert raises an exception

View code on GitHub.

Output:

AssertionError: string is not hello

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.