Unit 14Exception Handling in Python Programming
Follows IGNOU MCS-201, Unit 14
Even a correct program can fail at run time: a user types letters where a number is expected, a file is missing, a network is down. In C, such problems lead to error codes that are easy to ignore, or to undefined behaviour. Python reports them as exceptions, objects that describe what went wrong, and lets the program catch them and respond. This unit explains how the default exception handler stops a program, how to catch exceptions with try and except, how else and finally complete the picture, and how to raise your own exceptions, including exception classes you define yourself.
In this unit you will learn to
- Distinguish syntax errors from exceptions and name the common built-in exceptions.
- Read a traceback and explain what the default exception handler does.
- Catch exceptions with
tryandexcept, handle several types, and access the exception object. - Use
elseandfinally, and nesttrystatements. - Raise built-in exceptions with
raiseto report invalid situations. - Define and use your own exception classes.
Sections in this unit
- 14.1Errors and the Default Exception HandlerThe difference between syntax errors and run-time exceptions, the common built-in exceptions, and what Python does when an exception is not handled.9 min
- 14.2Catching Exceptions with try and exceptHandling exceptions with try and except, catching specific types, using the exception object, several except clauses, and the exception class hierarchy.12 min
- 14.3else, finally and Nested try StatementsCompleting the try statement with else and finally, when finally runs, typical clean-up uses, and how nested try statements pass exceptions outward.9 min
- 14.4Raising ExceptionsSignalling errors with the raise statement, choosing a suitable built-in exception, adding a message, and re-raising an exception after handling it.8 min
- 14.5User-Defined ExceptionsCreating your own exception classes by inheriting from Exception, adding a message and extra data, raising them, and catching them by class.8 min