Skip to content
IT Vizag
← Functions & Clean Code

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Errors and try/except

Lesson 5 of 9 · 2 min read

Handle bad input without crashing.

🎬 Video version coming soon — read it now

Programs meet bad input, missing files and network failures. Instead of crashing, you can catch errors and respond sensibly.

The basic shape

🔒 Code example: sign up free (above) to unlock it.

Python runs the try block. If a ValueError happens, it jumps to except instead of crashing.

Keep asking until it's right

Combine it with a loop and a function:

🔒 Code example: sign up free (above) to unlock it.

Now every place in your program that needs a number can use ask_int.

Catching different errors

🔒 Code example: sign up free (above) to unlock it.

else and finally

🔒 Code example: sign up free (above) to unlock it.

Don't catch everything

🔒 Code example: sign up free (above) to unlock it.

A bare except: with pass silences all errors, so the program "works" but quietly gives wrong results. Catch the specific error you expect and do something useful with it.

Raising your own errors

🔒 Code example: sign up free (above) to unlock it.

raise stops bad data early, with a clear message, instead of letting it cause strange bugs later.

Tip: Ask "what could go wrong here?" at every input(), file open and network call. Those are the places try/except belongs.

In one line

try runs risky code, except handles the specific errors you expect, and raise stops bad data with a clear message.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend