Handling an exception means placing the risky code in a try block and the recovery code in an except block. The program then continues normally instead of stopping.
The try statement
Syntax
try: code that might raise an exceptionexcept ExceptionType: code that runs if that exception occurs
How it runs:
The try block runs.
If no exception occurs, the except blocks are skipped.
If an exception occurs, the rest of the try block is skipped, and Python looks for the first except clause whose type matches. Its block runs, and the program continues after the whole try statement.
If no except clause matches, the exception travels outward, and if nobody handles it, the default handler stops the program.
except ExceptionType as e: gives the exception object a name, so you can print its message with print(e).
Several except clauses
Form
Catches
except ZeroDivisionError:
Only that type (and its subclasses)
except (ValueError, TypeError) as e:
Any of the listed types
except Exception as e:
Almost all errors (not KeyboardInterrupt or SystemExit)
except: (bare)
Absolutely everything, including Ctrl+C; avoid
Clauses are checked from top to bottom and only the first match runs, so put specific types before general ones. A bare except: must be the last clause, otherwise Python reports a SyntaxError.
The exception hierarchy
Every exception is an object of a class, and the classes form a hierarchy. An except clause catches its class and all its subclasses.
So except LookupError: catches both IndexError and KeyError, and except ArithmeticError: catches ZeroDivisionError.
Key takeaways
try holds risky code; except holds the handler.
Use specific exception types; group them with a tuple.
as err gives the exception object; print(err) shows its message.
An except for a class also catches its subclasses; order clauses from specific to general.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function read_age(text) that returns the age as an integer, or prints a message and returns None if the text is not a whole number.
Show worked answer
def read_age(text): with try: return int(text) and except ValueError: print("Age must be a whole number"); return None. For read_age("31") it returns 31; for read_age("thirty") it prints the message and returns None. Only ValueError is caught, because that is the error int() raises for unconvertible text; other mistakes would still be reported.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/exception-handling-in-python-programming/catching-exceptions-with-try-and-except/ to read this page.