12 - Exceptions
COMP 125 – Programming with Python
Recording Disclaimer
The synchronous sessions are recorded (audiovisual recordings). The students are not required to keep their
cameras on during class.
The audiovisual recordings, presentations, readings and any other works offered as the course materials aim
to support remote and online learning. They are only for the personal use of the students. Further use of
course materials other than the personal and educational purposes as defined in this disclaimer, such as
making copies, reproductions, replications, submission and sharing on different platforms including the digital
ones or commercial usages are strictly prohibited and illegal.
The persons violating the above-mentioned prohibitions can be subject to the administrative, civil, and
criminal sanctions under the Law on Higher Education Nr. 2547, the By-Law on Disciplinary Matters of Higher
Education Students, the Law on Intellectual Property Nr. 5846, the Criminal Law Nr. 5237, the Law on
Obligations Nr. 6098, and any other relevant legislation.
The academic expressions, views, and discussions in the course materials including the audio-visual
recordings fall within the scope of the freedom of science and art.
COMP 125 Programming with Python 2
Exceptions and exception handling
▪ Lots of things can go wrong in computer programs
▪ For example, you may try to
▪ Convert a string with non-digit characters to an integer
▪ Call a non-existent function of a class These are examples
▪ Import a non-existent module of exceptions
▪ Open a non-existent file
▪ Modify an immutable object
Should our programs
stop or handle these
exceptions?
COMP 125 Programming with Python 3
Exceptions
▪ Indication of a “special event”, usually an error, during program execution
▪ Exceptions cause the program to abruptly halt, unless handled
▪ Traceback:
▪ Occurs when an exception is encountered
▪ Error messages give information regarding the line numbers that caused the exception
▪ Indicates the type of exception and brief description of the error that caused exception to be raised
COMP 125 Programming with Python 4
Exception handling
▪ We must first “anticipate” an exception (including its type), then write code
to “catch” it, and handle it
▪ The try-except statement
try:
statements_that_may_cause_an_exception
except ExceptionType:
statements_to_handle_the_exception
▪ The code in the except part is called the exception handler
COMP 125 Programming with Python 5
Exception handling
▪ Can have multiple except clauses
▪ Can handle multiple exceptions in a single
except block
▪ Can get the exception object with as
▪ A lonely except catches “everything”
Source: Real Python
COMP 125 Programming with Python 6
Example
COMP 125 Programming with Python 7