Python Tutorial: Using Try/Except Blocks for Error Handling

///Python Tutorial: Using Try/Except Blocks for Error Handling

Python Tutorial: Using Try/Except Blocks for Error Handling

FavoriteLoadingAdd to favorites

We’ve all run into errors and exceptions while writing Python programs. In this video, we will learn how we can handle exceptions in specific ways and also look at the control flow of a try/except/else/finally statement. Understanding how to properly handle errors will provide us with the tools to make better software in the future. Let’s get started.

The code from this video can be found at:

✅ Support My Channel Through Patreon:

✅ Become a Channel Member:

✅ One-Time Contribution Through PayPal:

✅ Cryptocurrency Donations:
Bitcoin Wallet – 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet – 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet – MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

✅ Corey’s Public Amazon Wishlist

✅ Equipment I Use and Books I Recommend:

▶️ You Can Find Me On:
My Website –
My Second Channel –
Facebook –
Twitter –
Instagram –

#Python

source

By |2019-08-31T22:33:10+00:00August 31st, 2019|Python Video Tutorials|38 Comments

38 Comments

  1. Saicharan Venkateswarlu August 31, 2019 at 10:33 pm - Reply

    For keyerror in dictionary what if two errors occurs at the same time and which will be handled first

  2. Yue Zhao August 31, 2019 at 10:33 pm - Reply

    very nice video. many thanks!
    If I wrote codes outside the try block, is it equivalent to putting the codes inside the finally block?

  3. Reneeke9 August 31, 2019 at 10:33 pm - Reply

    Hi Corey, I want to use exceptions in a class, is that possible?
    I need to throw a message when the user is not initalizing the instance in the right way. They have to input a date, so that's Always tricky. Here's the code:

    class Wedstrijd(object):

    try:

    def __init__(self, plaats, year,month,day, vertrekpunt, hour,minutes):

    """ please define the location, year(yyyy), month(mm), day(dd), leaving point, leaving hour(hh) and leaving minutes(mm) """

    import datetime

    self.plaats = plaats

    self.datum = datetime.date(year,month,day)

    self.vertrekpunt = vertrekpunt

    self.vertrektijd = datetime.time(hour,minutes)

    except TypeError:

    help(Wedstrijd.__init__)

    test = Wedstrijd('limburg', 2019,4,'Maastricht', 15,1)

    print(test.vertrektijd)

    print(test.datum)

    Instead of running the except bloek, it just gives me the TypeError:

    TypeError: __init__() missing 1 required positional argument: 'minutes'

    Why doesn't it run the exception block in this class?

  4. Chris Keo August 31, 2019 at 10:33 pm - Reply

    Why would you want to raise an exception

  5. carlos max August 31, 2019 at 10:33 pm - Reply

    I'm failing to handle errors on loops, anyone to recommend me of an example I can refer to.plz

  6. Sagnik Dutta August 31, 2019 at 10:33 pm - Reply

    Awesome!!!

  7. Balaji Rajokkiyam August 31, 2019 at 10:33 pm - Reply

    @9:45 I think its not working any more in Python 3. Instead of getting to the "Exception" block it prints from the "FileNotFoundError" block. Unless you move the "Exception" block above the "FNFR" block the same message gets printed.

  8. Mohinder Pal Singh August 31, 2019 at 10:33 pm - Reply

    How to give custom error message on raise exception?

  9. KaiDing Zhou August 31, 2019 at 10:33 pm - Reply

    >>> hi, your video is extremely helpful

  10. Juehuan Liu August 31, 2019 at 10:33 pm - Reply

    does 'finally' must execute? for example: the 'try' is in a loop and there is 'continue' somewhere above. Thank you!

  11. Tumul Sharma August 31, 2019 at 10:33 pm - Reply

    thanks a lot Sir!

  12. Renhua Luo August 31, 2019 at 10:33 pm - Reply

    Sir
    How to uncomment code like the way you do. Thats so cool!

  13. Bikesh Tiwari August 31, 2019 at 10:33 pm - Reply

    You made me learn many concepts in python. Ur awesone teacher

  14. M S August 31, 2019 at 10:33 pm - Reply

    Thanks for the lesson Corey !

  15. Dmitri Rs August 31, 2019 at 10:33 pm - Reply

    I did an improved version of the game xd, but thanks for the idea.

  16. GTrack August 31, 2019 at 10:33 pm - Reply

    Thanks for the video. I learned Exception handling from here.

  17. info ce August 31, 2019 at 10:33 pm - Reply

    Thank you for great tutorials Corey! I want to tell you that can you remove django & flask tutorial videos from "Python Tutorials" PLAYLIST ? They are already in their playlist. We don't want to face with them while learning python basics.

  18. Oceans Blue August 31, 2019 at 10:33 pm - Reply

    @ min 8:25 what do you mean by make sure you close down the DB?

  19. WhiteWolf August 31, 2019 at 10:33 pm - Reply

    I got only one question Corey. Where I can read about exception types, the ones like 'FileNotFoundError'

  20. Jeremy Palmer August 31, 2019 at 10:33 pm - Reply

    I am curious, what is the advantage of "finally", why would you not just drop down out of the try block and execute the next piece of code?

  21. alexandru cretu August 31, 2019 at 10:33 pm - Reply

    Your videos are very helpful, Corey! tyvm
    Also, just to point out that it is better to close the file (f.close()) within the finally block, because it will be executed anyway, while the else block runs only if the try clause doesn't raise an exception.

  22. Nauman Tariq August 31, 2019 at 10:33 pm - Reply

    Very nice 👏👏

  23. Bho Loo August 31, 2019 at 10:33 pm - Reply

    Superb

  24. Kim Cato August 31, 2019 at 10:33 pm - Reply

    I love your videos! They are very well explained and short… better than my professor's. I am writing better programs because of your videos. Your videos are a GOD send.

  25. Alex Berk August 31, 2019 at 10:33 pm - Reply

    I don't get, why waht is purpose of 'finally' if you can just put the code after the 'try' block. Someone, please, explain what am i missing here?

  26. Vince de Jong August 31, 2019 at 10:33 pm - Reply

    ty

  27. Manoj Kumar August 31, 2019 at 10:33 pm - Reply

    Excellent explanation as to when to use this.Also by showing an example the concept just sits in head 🙂 Good job Corey

  28. Trey TONG August 31, 2019 at 10:33 pm - Reply

    your explaining is GOD of explaining!! The best ever

  29. WitherFallGaming 8 August 31, 2019 at 10:33 pm - Reply

    This video Helped ALOT! in my game development

  30. d p August 31, 2019 at 10:33 pm - Reply

    word = 'currupt'
    try:
    if word != 'corrupt':
    raise ValueError
    except ValueError:
    print("Corrupt is spelled wrong!")

    >>> Corrupt is spelled wrong!

    😀

  31. Isaac Lee August 31, 2019 at 10:33 pm - Reply

    Hi Corey Schafer

    I have a question for python

    I don't how to do my homework

    my homework is – write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7,2,bob,10 and 4 and match the output below.

    Invalid input

    Maximum is 10

    Minimum is 2

    This is my work

    largest = None

    smallest = None

    while True:

    num = input ('Enter a number')

    if num == 'done' : break

    try:

    number = float(num)

    except:

    print('Invalid input')

    for value in (number):

    if largest is None :

    largest = value

    elif float(value) < float(largest):

    largest = value

    print('Maximum is' ,largest)

    for value in (number):

    if smallest is None:

    smallest = value

    elif float(value) > float(smallest):

    smallest = value

    print('Minimun is' ,smallest)

    but the output is not

    Invalid input

    Maximum is 10

    Minimum is 2

    I want to know where is wrong

    Please help me

  32. Moaz El-sawaf August 31, 2019 at 10:33 pm - Reply

    Thanks a lot sir ❤

  33. Kabelo Mayisa August 31, 2019 at 10:33 pm - Reply

    really helpful … thank you !!

  34. Philipp Frögel August 31, 2019 at 10:33 pm - Reply

    such a good video!

  35. CHETAN VASHISTH August 31, 2019 at 10:33 pm - Reply

    Now that's how to explain. Well done Corey😄😄😄😄🍻

  36. Fiziwee August 31, 2019 at 10:33 pm - Reply

    5:32 if the file is not found, why does this execute the second error code and not the first one? The first exception is FileNotFoundError, so why is that not executed?

  37. negativeone August 31, 2019 at 10:33 pm - Reply

    This the best explanation of try / except concept ever.

  38. Opiyo Sebastian August 31, 2019 at 10:33 pm - Reply

    Thank you Corey….I continue to follow and grow as a self made developer. You my best teacher!!

Leave A Comment

*