Check out a free preview of the full Intermediate Python course

The "Practice: Exceptions" Lesson is part of the full, Intermediate Python course featured in this preview video. Here's what you'd learn in this lesson:

Nina live-codes the practice where syntax errors, custom exceptions, and other exception topics from previous sections are reviewed.

Preview
Close

Transcript from the "Practice: Exceptions" Lesson

[00:00:04]
>> Nina: We're gonna do an exercise where we cover our syntax errors, our custom exceptions. Talk about try accept and see how we might be able to reraise errors. Some common types of exceptions we’ve seen, if I try to define a function and I don’t put in the right indentation, I’ll get an indentation error here.

[00:00:31]
We saw SyntaxError yesterday, it's a little bit harder to trigger a syntax error for a list here. But let's say I did something like that, that's a SyntaxEerror, invalid syntax, I didn't put in the value. If I tried to do this and I forgot the comma between the last two values, also a SyntaxError.

[00:01:00]
So it's some common exceptions that we might see, 1 divided 0, that's that ZeroDivisonError that we've seen.
>> Nina: And some of those other common exceptions are TypeError. So if we try to add an integer and a string, that's an unsupported operand, right? We would need to call str on that number before we can concatenate them together.

[00:01:37]
ValueError, like we saw earlier, if I try to make integer out of a string a, it's a ValueError. It's saying, I don't know what this, is this a number? And lastly, the KeyError. So if I try to make a dictionary,
>> Nina: With a hello for the key and a world as the value for that key, and I try to use a key that doesn't exist, I'm gonna get a KeyError.

[00:02:12]
In terms of raising our own exceptions, the classes that we make,
>> Nina: Should inherit from Exception and generally end with, usually you'll see Error, very occasionally you'll see Exception. But usually naming these error is more common, as you've seen the TypeError, ValueError, KeyError, etc. So to follow that convention, let me name this MyError, and subclass from Exception.

[00:02:48]
Do I need to have anything in this class, or can it just be empty, right? And to throw, or to raise this exception, I use the raise keyword.
>> Nina: And that'll generate that trace back there.
>> Nina: I can also make my own custom exceptions a little bit fancier.

[00:03:11]
So I can say, class MyError(Exception) and provide my own constructor. I'm going to say self and message.
>> Nina: Now, I'm gonna change my message, and it's gonna say, ERROR system failure. That means it's a really serious error,
>> Nina: Followed by the message,
>> Nina: Okay, and what do I need to do so that my new message is propagated up?

[00:04:01]
>> Speaker 2: [INAUDIBLE] super.
>> Nina: Super, right. And super will call the constructor which class?
>> Speaker 2: Exception.
>> Nina: Exception, right. So we're gonna need to call .init there and we're gonna pass in our new message. Now, if I raise myError, is this gonna work?
>> Nina: It won't because message is required and I did not provide one.

[00:04:32]
So I'm gonna provide a helpful error message here, wow. Okay, and that's what we get. Programming is very serious, it's very serious business, no laughing allowed in this class. Just kidding. Okay, try and except. If I have a dictionary here,
>> Nina: The key is "Hello" and the value for that key is world.

[00:05:04]
I can try to print out my dictionary, look for random key. It's not in there, right? So what do I want to catch in this instance, which type? KeyError, yeah.
>> Nina: Oops, I think I messed up my, let's see. Right here, forgot that closing parenthesis. Okay, I'm gonna except on KeyError and print, no key found.

[00:05:43]
>> Nina: Okay, works as expected. I can also add a label to that exception if I wanted to do anything with it. Generally more useful for our own custom exceptions, right? Let's say I was going to try getting some random key here, and I could except on KeyError. And how do I give a variable name to that error.

[00:06:19]
>> Speaker 2: As.
>> Nina: Right, as. I'm gonna say as e, and now I can print out an f string and it will say, No! the key doesn't exist, and I can say error was.
>> Nina: We can also reraise exceptions, so catching a runtime error or something, and then raising one of our own custom exceptions.

[00:07:02]
That might be a good case for one. So I had the class, MyException.
>> Nina: And just as a reminder here,when I raise my exception,
>> Nina: And got that, oops I'm sorry, I called it my_error.
>> Nina: When I raised my error I get this very helpful message, right? So,

[00:07:38]
>> Nina: Maybe what I wanna do here is I'm gonna loop over a range of numbers and I'm gonna do that in reverse. So if I call range with 0 and 5 and -1, and I'm gonna show you this as a list. Sorry, that's not what I want. I wanna start at 5, go to 0.

[00:08:14]
So if I wanted to go through a range of numbers in reverse, I would do the end value first, the start value second. So kind of flip that around and then pass in a negative number here.
>> Nina: And as a reminder, that second argument is not inclusive. And so if I want to go to 0, I'm gonna have to put -1 there, right?

[00:08:44]
So I'm going to loop over this.
>> Nina: And say, for num in this range, print out,
>> Nina: 5 divided by the number.
>> Nina: And eventually it's gonna get to zero and say ZeroDivisionError. So instead,
>> Nina: I can put this whole thing in a try, right, and print out 5 divided by the number.

[00:09:25]
Okay, just to show you, we had MyError that I can raise, and,
>> Nina: I'm gonna loop over this list of numbers. And now I'm gonna put this in a try block. And I'm gonna say, try to divide 5 by that number. I'm going to except on the ZeroDivisionError.

[00:09:50]
>> Nina: And then I'm gonna raise a different type of error. I'm gonna raise MyError and say, lulz you tried to divide by zero.
>> Nina: Okay, so we'll see that in the REPL, it'll say during the handling of that exception another exception occurred. You won't see that particular detail in your tracebacks when you run Python programs.

[00:10:21]
So this exception cused another one, and I reraised, I caught this one and I raised another one. And so what are you trying to do here?

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now