Programs meet unexpected situations: a missing file, a wrong input, a lost connection. Python exception handling lets your program respond clearly instead of stopping with an error.
try and except
Put the code that may fail inside try. Handle a specific error inside except, such as FileNotFoundError or ValueError. Avoid a bare except that hides every error.
else and finally
- else runs only when no error happened.
- finally always runs, which is useful for closing files or connections.
Raising your own errors
Use raise when input breaks a rule, such as a negative age. A clear error message helps whoever calls your function.
Practice
Write a function that reads a number from the user and keeps asking until a valid number is entered. Handle ValueError and print a friendly message.
Next step: see our Python Full Stack course at ScholarLogic, or book a free demo class. A counsellor will share the fee and the next batch dates.
