Lab 8

Exceptions and testing

CS1302 Introduction to computer programming

Motivation of handling exception

When will the exception occur?

DevisioinByZeroError

IndexError

It is tedious and time-consuming to debug if the structure of the program is perplexing

What are exceptions?

An exception is a special object that the program can create when it encounters an extraordinary situation, usually some sort of run-time error

Common exceptional situations:

  • Attempting to read past the end of a file

  • Convert a non-numeric string to a number

  • A sequence(list,tuple) Index is out of range

Two ways of handling

First: look before you leap

Second: easier to ask for forgiveness than permission

Pros&Cons of two approaches

LPYL

  • Not robust
  • Difficult to implement

EAFP

  • Robust
  • Easy to implement
1

Basic structure of handling exception

Why do we need the finally block? 

Execution flow of the try/except statement

Handling mulitiple exceptions

Why we need to handle mutliple excpetions?

Raising Exceptions

Meaning of creating your own excpeiton?

Using Exceptions wisely

Is the use of exception necessary?

CS1302 Lecture 8 Chapter 12

By Chung Chan

CS1302 Lecture 8 Chapter 12

  • 115