Loading video player…

Using raise for Effective Exceptions (Overview)

In your Python journey, you’ll come across situations where you need to signal that something is going wrong in your code. For example, maybe a file doesn’t exist, a network or database connection fails, or your code gets invalid input. A common approach to tackle these issues is to raise an exception, notifying the user that an error has occurred. That’s what Python’s raise statement is for.

Learning about the raise statement allows you to effectively handle errors and exceptional situations in your code. This way, you’ll develop more robust programs and higher-quality code.

In this video course, you’ll learn how to:

  • Raise exceptions in Python using the raise statement
  • Decide which exceptions to raise and when to raise them in your code
  • Explore common use cases for raising exceptions in Python
  • Apply best practices for raising exceptions in your Python code
Download

Sample Code (.zip)

3.3 KB
Download

Course Slides (.pdf)

978.5 KB

00:00 Welcome to using Python’s raise for Effective Exceptions. My name is Christopher and I will be your guide. This course introduces you to exceptions, a language feature most commonly used for error handling and the raise keyword that causes an exception to fire off.

00:17 In this course, you’ll learn about exception objects, what it means to raise an exception, the exceptions that come with Python, how to write your own exception classes, how to chain exceptions together, and the relatively new language feature, exception groups.

00:38 The code in this course was tested using Python 3.12. Most of the code will work in any Python 3, except, see what I did there, for exception groups and the add_note feature, both of which were added in Python 3.11.

00:54 Those will be pointed out as I go along.

00:57 Exceptions are a key part to how code flow happens in Python. Their purpose is to cause a code block to be interrupted. Their most common use is error handling.

01:09 If something goes wrong in a code block, an exception gets raised to signal an interruption, the control flow in the block is stopped and then resumes inside of a handling block.

01:21 This is why exceptions mostly get used for error handling. It allows you to take action immediately after an error without needing to write error checking code after every single statement in a block.

01:34 The exceptions that your handling code deals with might be from libraries, or you can write your own exceptions as well. By the end of this course, you’ll have seen several examples of how exceptions get used, the various ways of using the raise keyword and some of the newer exception features added in Python as of 3.11.

01:56 Alright, that’s the gist. Next up, let’s dive into the exception object.

Become a Member to join the conversation.