๐Ÿ‡ฌ๐Ÿ‡ง Limited Time โ€” UK Onlyยท๐ŸŽ“ Free Learning for 1 Monthยท๐Ÿค– Free AI Training Includedยท๐Ÿ“š 4,000+ Lessons ยท 35,000+ Quizzesยท๐Ÿ† GCSE Mocks ยท Olympiad Papersยทโšก Selected Students Only ยท Limited Placesยท๐ŸŽ Free Value Worth ยฃ2,000ยท๐Ÿ‡ฌ๐Ÿ‡ง Limited Time โ€” UK Onlyยท๐ŸŽ“ Free Learning for 1 Monthยท๐Ÿค– Free AI Training Includedยท๐Ÿ“š 4,000+ Lessons ยท 35,000+ Quizzesยท๐Ÿ† GCSE Mocks ยท Olympiad Papersยทโšก Selected Students Only ยท Limited Placesยท๐ŸŽ Free Value Worth ยฃ2,000ยท๐Ÿ‡ฌ๐Ÿ‡ง Limited Time โ€” UK Onlyยท๐ŸŽ“ Free Learning for 1 Monthยท๐Ÿค– Free AI Training Includedยท๐Ÿ“š 4,000+ Lessons ยท 35,000+ Quizzesยท๐Ÿ† GCSE Mocks ยท Olympiad Papersยทโšก Selected Students Only ยท Limited Placesยท๐ŸŽ Free Value Worth ยฃ2,000ยท
๐Ÿ Python

Try and Except

๐Ÿ“š What is Try/Except? Pythia says: 'Even the best code faces unexpected situations - a file that does not exist, a user who types letters instead of numbers. try/except is your safety net!'

8 min 10 XP Lesson 11 of 21
Try and Except
๐ŸŒ

Appy Saysโ€ฆ

What happens when your app crashes because a user typed a word where a number was expected? Without try/except, your whole program stops. With it, you catch the problem, show a friendly message, and keep running. This is how real apps stay alive.

๐Ÿ“–

What is try/except?

try/except is Python's error-handling mechanism. You put risky code in a try block. If an error (called an exception) occurs, Python jumps to the except block instead of crashing.

  • โ€ขtry: โ€” the risky code goes here
  • โ€ขexcept ExceptionType: โ€” code that runs if that error occurs
  • โ€ขexcept Exception as e: โ€” catch any error and get its message in e
  • โ€ขelse: โ€” runs only if NO error occurred
  • โ€ขfinally: โ€” always runs, whether or not there was an error (great for cleanup)
  • โ€ขCommon exceptions: ValueError, TypeError, FileNotFoundError, ZeroDivisionError
๐ŸŽฎ

Think of it like Roblox respawn

In Roblox, when your character falls off the map, the game doesn't close โ€” you respawn. try/except is your code's respawn system. When something goes wrong, instead of the whole program dying, you catch the fall and safely recover.

โš™๏ธ

How It Works

  • โ€ข1. Python tries every line in the try block one by one
  • โ€ข2. If a line raises an exception, Python immediately jumps to the matching except
  • โ€ข3. Lines after the error in try are skipped
  • โ€ข4. If no exception occurs, the except block is skipped entirely
  • โ€ข5. finally always runs last โ€” use it to close files or database connections
  • โ€ข6. You can have multiple except blocks for different error types
๐ŸŒ

Real-World Examples

  • โ€ขA banking app wraps every transaction in try/except so a database error doesn't freeze the whole app
  • โ€ขSpotify uses error handling when fetching album art โ€” if the image fails to load, it shows a placeholder
  • โ€ขYouTube catches FileNotFoundError when a video has been deleted but someone tries to share the old link
  • โ€ขWhatsApp catches ConnectionError when your phone loses signal mid-message and queues the message to retry
๐Ÿ’ก

Key Facts

  • โ€ขExceptions are objects in Python โ€” they have a .args and .__class__.__name__
  • โ€ขYou can raise your own exceptions: raise ValueError("Age must be positive")
  • โ€ขCatching bare except: (no type) is bad practice โ€” it hides bugs you didn't intend to catch
  • โ€ขtry/except has almost zero performance cost when no error occurs
โš ๏ธ

Watch Out!

Never write except: pass โ€” this silently swallows all errors, including ones you didn't expect. Always catch specific exceptions (like ValueError) or at least except Exception as e: print(e) so you know what went wrong.

๐Ÿ“Œ

Remember

Use try/except wherever user input or external data (files, APIs, networks) is involved โ€” those are the places your code is most likely to get unexpected values.

โœ…

What You Learned

  • โ€ขtry/except catches errors so your program keeps running
  • โ€ขCatch specific exception types โ€” never use bare except: pass
  • โ€ขUnlocks: robust user input handling, safe file reading, resilient API calls

Key Facts

  • โ†’Exceptions are objects in Python โ€” they have a .args and .__class__.__name__
  • โ†’You can raise your own exceptions: raise ValueError("Age must be positive")
  • โ†’Catching bare except: (no type) is bad practice โ€” it hides bugs you didn't intend to catch
  • โ†’try/except has almost zero performance cost when no error occurs

Real-World Examples

โ€ข A banking app wraps every transaction in <code>try/except</code> so a database error doesn't freeze the whole app โ€ข Spotify uses error handling when fetching album art โ€” if the image fails to load, it shows a placeholder โ€ข YouTube catches <code>FileNotFoundError</code> when a video has been deleted but someone tries to share the old link โ€ข WhatsApp catches <code>ConnectionError</code> when your phone loses signal mid-message and queues the message to retry

Remember

Use try/except wherever user input or external data (files, APIs, networks) is involved โ€” those are the places your code is most likely to get unexpected values.

Quick Quiz

1 / 3

try/except is for?