Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Introduction to Exceptions

Give Feedback

This lesson introduces exceptions and exception handling in Python. You will learn:

  • What exceptions are
  • How to throw exceptions with detailed error messages
  • Best practices to follow when writing exceptions
  • Subtleties to be aware of when catching multiple exceptions

00:00 We’ll be discussing how you handle situations where things go wrong, how to recover from such failures in a graceful manner, as well as create your own exceptions when the need arises.

00:08 We’ll also cover things like raising exceptions, as well as catching and handling them, as well as things you should do after you’ve raised and caught exceptions.

00:17 So, the first thing to know before you end up handling exceptions is how to throw one. So let’s say you know that in a particular case your code will throw a particular exception or you want to throw a particular exception to signify some action that needs to be taken.

00:33 What you simply do is use the raise command and then you pass a particular exception. In this case, I’m just going to call Exception, but you can call many others. You can call a RuntimeError, for example.

00:46 And all those are in the standard library, no need to import them, it raises a command and all these are in the standard library so you can just use them as is. So when our main() is called, it’ll immediately call RuntimeError, as you’ll see.

01:00 And then you’ll see that a RuntimeError was thrown. You can also pass optional arguments, 'this does not work'.

01:09 And it will simply pass that along to the user saying RuntimeError with the particular message that you have. So, these messages allow you to customize what these particular generic exceptions are actually being thrown for, so you can pass in information about where you were in the code, some logging information that you may need, which we’ll get into in another screencast.

01:30 But this is generally how you raise an exception for cases where you think it might be applicable.

01:38 So, let’s quickly just write a quick example on how to run a particular exception. Let’s just rename this method to division().

01:47 We are then going to have two numbers that are passed to division(). We’re going to call those x and y. And we are going to then try: So, when you’re entering a portion of code where you think an exception may happen, or it isn’t straightforward, what you want to do is wrap it in a try/catch block.

02:06 This try/catch block says, “Try whatever is in this block, and if it fails, raise an exception or catch an exception.” For example, we’re going to try to divide x by y.

02:22 And we’re going to except on everything, in this particular case, and we’re going to go print 'exception happened'.

02:33 Now, once that happens, we want to just quickly rename this to division(), and we’re going to pass a 4 and a 0. So, the wiser of you will see quickly that when dividing 4 by 0, it’s not possible. You can’t divide by 0, so it should throw an error.

02:52 And as you can see, an exception happened. There are two particular things to note here. Last time when we raised the RuntimeError, we saw that there was a RuntimeError being raised and there was information provided. Here, as you can see, there is nothing provided other than the print statement that we decided to run on the except block. That being said, oftentimes you’ll see things like people trying something and then passing on the exception. So when the exception actually happens, nothing happens, the program continues its execution.

03:22 Now, this is a horrible practice and you should avoid this always. There may be very few cases that this may be acceptable, but you should always re-raise your exception so that it is logged and then the user or the debugger of your program can see what’s going on and why a particular thing just stops working. Because if you do this, what ends up happening is the program just returns quietly and you don’t have any idea where the thing’s happening, and this can lead to very subtle bugs and problems.

03:52 So always be explicit as to what you want to do and how you want to do it. That brings me to my second point. This exception, here, except without any arguments passed in front of it deals with all exceptions.

04:05 So if I were to change this to x.goo, which x does not have an attribute called .goo, and I were to except: pass, it would just mask the AttributeError as well.

04:19 Now, we’re going to go into delving into this a little bit further. We’re going to remove this and we are then going to go make sure this except catches ZeroDivisionError.

04:31 So as you can see, this highlighted up and it’s going to catch all errors that deal with dividing by zero. 'Division by Zero is not allowed'.

04:47 That being said, it catches that and then prints that particular exception. Now, we can catch multiple exceptions on the same line, so AttributeError, for example.

04:59 And we can then do something like this. x.goo, which doesn’t exist, will cause an AttributeError.

05:08 I thought you need to put this there, so now I’ve just come across a subtlety in exceptions. You need to put them in a tuple, so it knows to look for those particular types.

05:19 But then when I did that, it then catches the AttributeError as well, which happens first and is what causes the exception. And then again, Division by Zero is printed. Now, before I discuss the point here about the issue I just ran into, I would like to first emphasize that the same message will be printed out for both ZeroDivisionError and AttributeError.

05:41 If you want to separate these out, you can have as many excepts as you like. So we can do this, we can go, except again, AttributeError: print 'you did something wrong jack'.

06:00 And as you can see, it’ll print the exception there. So previously, when I was writing out the example, I accidentally made the mistake of doing this. What that means is when you except, assign the exception to a variable called AttributeError, so if I were to go ahead and print AttributeError here.

06:20 What will happen is if we remove this and then except again, you’ll see that we print out the meaning of that exception, which is integer division or modulo by zero, which isn’t allowed, so I assigned this as that.

06:36 What you normally would do is have it as an err here, and then you can print err here and that is what’s run there. And that is the subtlety that you have to be aware of when handling multiple exceptions in the same block.

bienshijoe on Jan. 11, 2021

Hello, does exception handle in Python version 2.7 is same as Python version 3.9?

Become a Member to join the conversation.