Table of Contents
Exceptions are errors in our program that causes Python to stop and display an error message. Exceptions are handled using the try-except-finally block.
We want to avoid catastrophic errors.
Exception Handling
As mentioned before, we handle exceptions using the try-except-finally block. The try
block is where you put the code that could potentially throw an exception. The except
block is where you can gracefully perform an action if an exception was indeed thrown. Lastly, the finally
block allows you to run code no matter if an exception was thrown or not.
Let's look at a very simple exception:
PYTHONtry:
print(sabe)
except:
print("An exception occurred.")
BASHAn exception occurred.
In our piece of code, the variable sabe
was purposely not defined. This threw an exception which we handled inside our except
block.
Notice how we didn't use a finally
block because they are entirely optional. However, we could use one anyway like this:
PYTHONtry:
print(sabe)
except:
print("An exception occurred.")
finally:
print("Moving on!")
BASHAn exception occurred.
Moving on!
Multiple Exceptions
You can handle multiple exceptions by chaining the except
blocks and specifying what error you want to handle.
Here's how that looks:
PYTHONtry:
print(sabe)
except OverflowError:
print("An overflow occurred.")
except:
print("An exception occurred.")
finally:
print("Moving on!")
BASHAn exception occurred.
Moving on!
Else
You can use the else
block to run code when no exceptions were thrown. This is similar to the finally
block except that the finally
block runs no matter what whereas the else
block runs only when the code was exception-free.
PYTHONtry:
print("Hello!")
except OverflowError:
print("An overflow occurred.")
except:
print("An exception occurred.")
else:
print("Great, no errors!")
finally:
print("Moving on!")
BASHHello!
Great, no errors!
Moving on!
Raising Exceptions
When the situation arises, you might want to raise an exception yourself. This is done using the raise
keyword:
PYTHONraise Exception("Sorry, this is an exception!")
BASHTraceback (most recent call last):
File "C:\Users\Sabe\sabe.py", line 1, in <module>
raise Exception("Sorry, this is an exception!")
Exception: Sorry, this is an exception!
This is useful especially if you're writing your own module because it allows users of your module to then handle your exceptions themselves and handle it however they want.
Resources
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor