ricardomol
  • Ricardomol Notes
  • Frontend
    • Javascript Toolchain
    • Javascript
      • Quirks
      • Articles
        • Function caching
        • 12 JS Tricks
      • Closures
      • Assorted
      • ES6
      • this
      • OOP
      • Async Programming
      • Functional Programming
      • Typescript
    • React
      • Patterns
        • Render props
      • React Router
    • Webpack
    • CSS
      • Resources
  • Backend
    • Python
      • Shallow copy vs deep copy
      • Classes
      • Resources
      • Python C Extensions
      • Coroutines
      • Exceptions
      • Context managers
      • One-Liners
      • Open function
      • Object introspection
      • Targeting Python 2 + 3
      • For - else
      • Comprehensions
      • Lambdas
      • __slots__ magic
      • Collections
      • Enumerate
      • Mutation
      • Map, Filter and Reduce
      • Decorators
      • Sets
      • Fluent Python summary
      • Quizes / Tips
      • Generators
    • Django
      • Generic Relations
      • FBV's vs CBV's
      • ORM
      • DRF
    • RESTful Architecture
    • Resources
  • Databases
    • Joins
    • Normalization
    • PostgreSQL
  • DevOps
    • Docker
      • 0. Resources
      • 2. Services
      • 3. Swarms
      • 5. Stacks
      • 6. Deploy your app
    • CI
      • CI with Django
    • CD
    • PaaS
    • WSGI servers
    • Django
      • Django Deployment
    • Modern DevOps with Django
  • Git
    • Git
  • Comp Sci
    • Big O Notation
    • Patterns
    • Programming paradigms
  • Assorted
    • TCP vs UDP
    • Tests
    • MongoDB
    • Node
      • Resources
    • Go
    • HTTP vs HTTP2
    • GraphQL
    • Books
    • Vim
    • IPv4 vs IPv6
    • Regex
    • Redis
    • Celery
      • Brokers
    • Caching
  • SECURITY
    • Security
Powered by GitBook
On this page
  • Exceptions
  • Handling multiple exceptions
  • 1. Putting all the exceptions in a tuple
  • 2. Separate except blocks
  • 3. Trapping ALL exceptions:
  • finally clause
  • try/else clause
  1. Backend
  2. Python

Exceptions

Exceptions

The code which can cause an exception to occur is put in the try block and the handling of the exception is implemented in the exceptblock.

Example:

try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))

Handling multiple exceptions

Three methods to handle multiple exceptions:

1. Putting all the exceptions in a tuple

try:
    file = open('test.txt', 'rb')
except (IOError, EOFError) as e:
    print("An error occurred. {}".format(e.args[-1]))

2. Separate except blocks

We can have as many except blocks as we want.

Example:

try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occurred.")
    raise e
except IOError as e:
    print("An error occurred.")
    raise e

If the exception is not handled by the first except block then it may be handled by a following block, or none at all.

3. Trapping ALL exceptions:

try:
    file = open('test.txt', 'rb')
except Exception as e:
    # Some logging if you want
    raise e

Helpful when you have no idea about the exceptions which may be thrown by your program.

finally clause

The code wrapped in thefinally clause will run whether or not an exception occurred.

Example: to perform clean-up after a script:

try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:
    print("This would be printed whether or not an exception occurred!")

# Output: An IOError occurred. No such file or directory
# This would be printed whether or not an exception occurred!

try/else clause

We might want some code to run if no exception occurs.

It would run before the finally clause.

Example:

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # any code that should only run if no exception occurs in the try,
    # but for which exceptions should NOT be caught
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs. And an error here would NOT be caught
# This would be printed in every case.
PreviousCoroutinesNextContext managers

Last updated 6 years ago