Python Mini-Course - PowerPoint PPT Presentation

About This Presentation
Title:

Python Mini-Course

Description:

Python Mini-Course: Lesson 19. 2. What is an exception? Exceptions are run-time errors ... a short program to divide two numbers. Include a routine to handle ... – PowerPoint PPT presentation

Number of Views:87
Avg rating:3.0/5.0
Slides: 12
Provided by: troys9
Learn more at: https://www.ou.edu
Category:
Tags: course | mini | python | the

less

Transcript and Presenter's Notes

Title: Python Mini-Course


1
Lesson 19Handling Exceptions
  • Python Mini-Course
  • University of Oklahoma
  • Department of Psychology

2
Lesson objectives
  1. Understand how exceptions are generated and
    handled in Python
  2. Use the raise statement to generate exceptions
  3. Use the tryexcept statement to intercept and
    handle exceptions
  4. List the common built-in exceptions

3
What is an exception?
  • Exceptions are run-time errors
  • Whenever the interpreter has a problem it
    notifies the user/programmer by raising an
    exception

4
Handling exceptions
  • By default, the interpreter handles exceptions by
    stopping the program and printing an error
    message
  • However, we can override this behavior by
    catching the exception

5
Example nocatch.py
  • fin open('bad_file')
  • for line in fin
  • print line
  • fin.close()

6
Example catch.py
  • try
  • fin open('bad_file')
  • for line in fin
  • print line
  • fin.close()
  • except
  • print 'Something went wrong.'

7
Catching specific problems
  • There are a number of kinds of exceptions,
    including
  • IndexError
  • EOFError
  • KeyError
  • SyntaxError
  • http//docs.python.org/library/exceptions.htmlblt
    in-exceptions

8
Example catch2.py
  • try
  • fin open('bad_file')
  • for line in fin
  • print line
  • fin.close()
  • except IOError
  • print 'Something went wrong.'

9
Error handling
  • Once you catch the error, you need to handle it
  • Perform an alternate action
  • Generate a customized error message and
    gracefully end the program

10
Raising exceptions
  • You can also create your own error generating and
    handling routines by raising an exception
  • Example
  • study147.py line 146

11
Exercise
  • Write a short program to divide two numbers
  • Include a routine to handle division by zero
Write a Comment
User Comments (0)
About PowerShow.com