Exception Handling
Write programs that respond gracefully to runtime errors instead of crashing. Understand the three types of programming error and how try/except/finally protects your code.
Imagine an ATM crashing with a cryptic error message because someone pressed Cancel at the wrong moment - or a hospital system going down because a nurse typed letters into a numeric field. Exception handling is what separates reliable software from fragile software.
raise / throw to signal that something has gone wrong.Three Types of Programming Error
You must be able to identify and distinguish between syntax, runtime and logic errors in the exam.
Example:
pint("hello") - misspelled keyword.The program will not run at all.
Example: dividing by zero, accessing an index that does not exist.
This is what exception handling catches.
Example: calculating average by dividing by
n+1 instead of n.Cannot be caught by exception handling - requires testing and debugging.
try / except / finally
Wrap potentially dangerous code in a try block. If an exception is raised, control jumps to the matching except (or catch) block. The finally block always runs regardless.
try: number = int(input("Enter a number: ")) result = 100 / number print(f"Result: {result}") except ValueError: print("Error: please enter a whole number.") except ZeroDivisionError: print("Error: cannot divide by zero.") finally: print("Calculation complete.") # always runs
try { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); double result = 100.0 / number; Console.WriteLine($"Result: {result}"); } catch (FormatException) { Console.WriteLine("Error: please enter a whole number."); } catch (DivideByZeroException) { Console.WriteLine("Error: cannot divide by zero."); } finally { Console.WriteLine("Calculation complete."); // always runs }
Catch more specific exceptions before more general ones. In Python, a bare except: catches everything - useful as a last resort but makes debugging harder because you cannot tell what went wrong. Always prefer named exception types.
Raising Exceptions Deliberately
You can raise an exception yourself when data is invalid, rather than letting the program continue with bad values. This makes bugs easier to find and fixes easier to make.
def set_age(age): if age < 0 or age > 130: raise ValueError(f"Age {age} is not valid.") return age try: set_age(-5) except ValueError as e: print(e) # Age -5 is not valid.
static int SetAge(int age) { if (age < 0 || age > 130) throw new ArgumentOutOfRangeException( "age", $"Age {age} is not valid."); return age; } try { SetAge(-5); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); }
Error Trigger Sandbox
Select a scenario to see how each exception type behaves - with and without a try/except block.
Three Quick Challenges
Trace through the try/except/finally carefully. What two lines are printed?
try: print(1 / 0) except ZeroDivisionError: print("caught") finally: print("done")
try { Console.WriteLine(1 / 0); } catch (DivideByZeroException) { Console.WriteLine("caught"); } finally { Console.WriteLine("done"); }
Complete the exception handler to catch a ValueError:
This code swallows an error silently. What is wrong with it?
try: result = int("abc") except: pass print(result)
Check Your Understanding
pint("hello"). What type of error is this?pint is not a valid Python keyword - this is a misspelling caught before the program runs, so it is a syntax error.finally block always executes. It is commonly used to close files or database connections so resources are never left open.len(numbers) + 1 instead of len(numbers). What type of error is this?int("hello")?ValueError is raised when a function receives the right type of argument but an inappropriate value - "hello" is a string (right type for conversion) but cannot be parsed as an integer.except ValueError) over a bare except:?except: catches every possible exception, including ones you did not anticipate. This can silently swallow serious bugs like KeyboardInterrupt, making programs very difficult to debug.Beyond the basics
What to do instead:
1. Catch the specific exception and show an honest error message to the user.
2. Log the full exception details (type, message, stack trace) to a secure server log for developers to investigate.
3. Roll back any partial database changes so the account balances stay consistent.
4. Never hide errors behind misleading success messages - exception handling should recover gracefully, not lie.
Practice and Consolidation
Programming Fundamentals Complete!
You have covered all 10 lessons - from variables and operators through to file handling and exception handling. Ready to test your full unit knowledge?
Back to series overviewexcept: that catches all errors? What problems can this hide?ValueError if the input is not a valid number. [3 marks]finally block does and give one situation where it is useful. [2 marks]