Exception Handling in Python
Class 12 · Computer Science
4 ideas in Class 12 Computer Science, explained in plain words, with games and quizzes to practise.
Syntax Errors versus Exceptions
Part of: Errors and exceptions in Python
A syntax error means the program breaks a grammar rule of Python, such as a missing colon or an unclosed bracket. Python spots it before running anything, so nothing executes until it is fixed. An exception is an error that pops up while a correct-looking program runs, such as opening a missing file or dividing by zero.
Why it matters. Knowing the difference tells a learner where to look for the fix. Grammar mistakes are fixed in the writing itself, while exceptions need planning for surprises during the run. Without this split, learners rerun code that can never start, or blame grammar for a fault that only appears with real data.
Key words
- Syntax Error
- : A break of a grammar rule of the language, found before the program runs.
- Exception
- : An error object raised while a program runs, such as a failed division.
- Parsing
- : The step where the interpreter reads the code and checks its grammar.
- Logical Error
- : A flaw in thinking that lets the program run but gives a wrong result.
- Interpreter
- : The tool that reads Python code and carries out its instructions.
Try it in two minutes
- Open a short program that misses a colon and run it. Ask what the message names.
- Fix the colon, run again, and enter zero as the divisor. Ask when this second error appeared.
- Ask your child to sort two faults into before-run and during-run: an unclosed bracket and a missing file.
Try at home. Ask your child to make one tiny program with a grammar slip and one that divides by zero, then explain which fault appears first and why.
Built-in Exceptions
Part of: Errors and exceptions in Python
Python already defines ready-made exceptions for common faults. Dividing by zero raises one kind, using a name that was never defined raises another, and asking for a list item past the end raises a third. Each name points to a different cause, so the message tells the programmer what to fix.
Why it matters. Reading the exception name is the fastest way to find a bug. A learner who matches each name to its cause fixes programs quickly instead of guessing. It also prepares them to write handlers for the right fault.
Key words
- Built-in Exception
- : A ready-made error type supplied by Python for a common fault.
- ZeroDivisionError
- : The exception raised when a divisor in a division is zero.
- ValueError
- : The exception raised when the type is right but the value is unsuitable.
- IndexError
- : The exception raised when a list position lies past the end.
- NameError
- : The exception raised when a used name was never defined.
- TypeError
- : The exception raised when an operation gets a wrong kind of data.
Try it in two minutes
- Divide a number by zero in interactive mode and read the exception name together.
- Use a made-up name in a line and read the new exception name. Ask how it differs.
- Make a three-item list and ask for the fifth item. Ask what the name tells us.
Try at home. Ask your child to cause three different built-in exceptions on purpose and note which name appears each time.
Raising Exceptions with raise and assert
Part of: Raising and handling exceptions
Sometimes a program must report a fault itself. The raise statement throws an exception at once, and no later line in that block runs. The assert statement tests a condition, often at the start of a function, and throws an AssertionError only when the test comes out false.
Why it matters. Deliberate raising lets a program reject bad data early with a clear message instead of failing mysteriously later. Learners who use raise and assert write safer functions and catch wrong inputs near their source.
Key words
- raise Statement
- : A line that throws an exception at once with an optional message.
- assert Statement
- : A check that throws an error only when its condition is false.
- AssertionError
- : The exception thrown by a failed assert check.
- Traceback
- : The report showing the chain of calls that led to the error.
Try it in two minutes
- Write a tiny block that raises an error message and note that the next line never runs.
- Add a check at the start of a squaring function that accepts only zero or more.
- Call it once with 100 and once with a negative number, and compare the two results.
Try at home. Ask your child to add a check to a pocket-money function so it rejects negative amounts with a clear message.
Handling Exceptions with try except else finally
Part of: Raising and handling exceptions
Risky lines go inside a guarded try part, and each matching handler part deals with one kind of error. A general handler with no name may sit last to catch anything left over. The success part runs only when nothing went wrong, and the closing finally part runs in all cases.
Why it matters. Guarded blocks keep programs alive when users type badly or files go missing. Learners who place handlers, success parts and closing parts correctly give clear messages and always tidy up, instead of letting the program crash.
Key words
- try Block
- : The guarded part holding lines where an error is suspected.
- except Block
- : A handler part that runs when its named error occurs.
- else Clause
- : An optional part that runs only when the guarded part had no error.
- finally Clause
- : A closing part that runs in every case, error or not.
- Exception Handler
- : Code built to deal with a specific raised exception.
Try it in two minutes
- Guard a division by the entered number with a handler for zero division.
- Run it once with 5 and once with zero, and note which parts run each time.
- Add a success part and a closing part, then predict what each run prints.
Try at home. Ask your child to guard a division program with two handlers, a success part and a closing part, then test it with good and bad inputs.
What your child will practise
- Built-in Exceptions: Ocean Quick Fire (Quick Fire)
- Handling Exceptions with try except else finally: Desert Puzzle (Clue Puzzle)
- Handling Exceptions with try except else finally: Jungle Quick Fire (Quick Fire)
- Raising Exceptions with raise and assert: Candy Quick Fire (Quick Fire)
- Syntax Errors versus Exceptions: Ocean Puzzle (Clue Puzzle)
- Quiz: Built-in Exceptions (8 questions)
- Quiz: Handling Exceptions with try except else finally (8 questions)
- Quiz: Raising Exceptions with raise and assert (8 questions)
- Quiz: Syntax Errors versus Exceptions (8 questions)