Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using the try and except Keywords

00:00 The try and except keywords. These are the ones you’ll need to handle errors.

00:06 In this lesson, you’re going to be covering the tryexcept structure. This is basically how to handle exceptions gracefully.

00:16 The syntax for this is the try keyword followed by a colon (:). Then you have your indented block afterwards.

00:25 Then after that indented block, you have an except keyword with a type of error. Now ValueError is a class of error, and then you have a colon after that as well.

00:38 And what this will do is that it will catch any ValueErrors that come out, and instead of raising that to the top level and stopping your program, it will catch it, and then it will print "That was not an integer".

00:51 It will run whatever’s in the indented block after the colon So to summarize that, you have try: and then an indented block, and then except with the type of error, colon, and then another indented block.

01:04 So it’s going to try to run what’s in the try indented block, and if it runs into an error and there is an except with the type of error, then it’s going to run whatever’s in that indented block, instead of just raising the error up to the top.

01:19 This example is quite common to see because you’re taking user input with the input() function, and you’re asking someone to enter an integer, and now they might enter "hello", which would raise a ValueError.

01:34 Thankfully, you’ve caught that ValueError, and instead of just raising this big stack trace that might not be legible to someone who doesn’t do any programming, it will just print "That was not an integer".

01:46 And you could wrap this whole thing in a loop to make sure that they eventually input an integer. Now you might be asking, how would you catch different types of errors?

01:58 You can do this by adding on except clauses after the try indented block. As you can see here, you have one, two except blocks that will catch different types of error.

02:12 One catches a TypeError, one catches a ZeroDivisionError.

02:17 This allows you to customize the behavior of your program for each type of error. So if someone tries to use this function with "hello" and a number, then they’d get a TypeError, and the result from that would be the execution of the print() function, which would print "Both arguments must be numbers".

02:38 If they try to pass in a num2 as 0, then they would get a ZeroDivisionError, and the program would print "num2 must not be 0".

02:51 Take a look at this in action. Here, you’ve got this operation on line 2, which is 1 / 0, and that’s in a tryexcept block.

03:01 So line 1, you have try with the colon and then line 2, you have the indented block with 1 / 0. On line 3, you have except zeroDivisonError with a colon. And in that indented block, you have print("I caught the error"). And on the line 6, finally, unindented, you have print("done"). Just run this with a F5, and as you can see it prints "I caught the error" and "done". You’ll note that anything after the 1 / 0 will not get printed.

03:29 So if you just add a call to the print() function after the 1 / 0 in the try indented block, you’ll see that that doesn’t get printed because once the error is raised, that indented block is done for.

03:44 And you’ll also note that the error doesn’t stop the whole program. So apart from printing "I caught the error" on line 5 in the indented block of the except statement, then on line 7, you have an unindented print("done"), which always prints.

04:00 This is in contrast to if you just do 1 / 0.

04:06 It will just stop the program in its tracks and give you a traceback with the ZeroDivisionError, which can be quite unreadable if you don’t have any experience or any inclination to learn programming, and you might be designing programs for your friends or colleagues to use, and they might not have any knowledge of programming.

04:27 There is a bit of a cheat code for the try and except block, and that’s using a bare except clause. You can use the except keyword without any error class after it. As you can see, there’s the except, and then immediately followed by the colon with no error class in between them.

04:46 This acts as a wild card and will catch any and all errors apart from SyntaxErrors. While you can do this, it’s generally considered bad practice to do so.

04:57 It’s a bad habit to get into. The Zen of Python says that explicit is better than implicit. And with error handling, it’s best to be very explicit about things that can go wrong.

05:08 If you default to using bare except clauses with generic error message, and your program grows, you’ll end up seeing these error messages a lot, and they won’t give you any clues as to what went wrong.

05:20 So if there is a problem in your program, it’s going to be very hard to debug. So in the same way that you should give your variables descriptive names, handle errors explicitly to save your future self and colleagues a lot of headaches. In this lesson, you’ve had the rundown on the tryexcept structure, and you’ve learned how to handle exceptions gracefully with this structure.

Avatar image for mallikarjunakamathamva

mallikarjunakamathamva on Dec. 2, 2023

Please provide some materials on when we should write the try and except block and when we should not write it.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Dec. 5, 2023

@mallikarjunakamathamva The written tutorial entitled Python Exceptions: An Introduction is good material on handling exceptions in Python, which contains a section dedicated to the try and except clauses.

Become a Member to join the conversation.