slide1 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
CS 112 Intro to Programming Exceptions PowerPoint Presentation
Download Presentation
CS 112 Intro to Programming Exceptions

Loading in 2 Seconds...

play fullscreen
1 / 28

CS 112 Intro to Programming Exceptions - PowerPoint PPT Presentation


  • 105 Views
  • Uploaded on

CS 112 Intro to Programming Exceptions. George Mason University. Exception Handling: Basic Syntax. try : #watch for exceptions here try_suite except : #exception handling code except_suite. A piece of code that is potential to crash in runtime. 2. Exceptions Hierarchy. BaseException

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'CS 112 Intro to Programming Exceptions' - kezia


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide1

CS 112

Intro to Programming

Exceptions

George Mason University

exception handling basic syntax
Exception Handling: Basic Syntax

try:#watch for exceptions heretry_suiteexcept:#exception handling codeexcept_suite

A piece of code that is

potential to crash in runtime

2

exceptions hierarchy
Exceptions Hierarchy

BaseException

+-- KeyboardInterrupt

+-- Exception

+-- ArithmeticError

| +-- ZeroDivisionError

+-- EnvironmentError

| +-- IOError

+-- EOFError

+-- LookupError

| +-- IndexError

| +-- KeyError

+-- NameError

+-- SyntaxError

+-- SystemError

+-- TypeError

+-- ValueError

  • There are many exception classes organized into a hierarchy→ using inheritance (parent and child class relationships)
  • (found at http://docs.python.org/3.2/library/exceptions.html)

Whenever a runtime error occur in ‘try’, the ‘except’ will handle this specific exception (event)

validating input
Validating Input

Loop continues to execute, raising and handling exceptions, until user complies.

validating input1
Validating Input

Loop continues to execute, raising and handling exceptions, until user complies.

demo$ python3 e4.py

#: 5

successfullygot x: 5

#: asdf

name 'asdf' is not defined

#: 3/0

division by zero

Exception1

Exception2

exception handling
Exception Handling

There are three basic choices when handling exceptions:

  • handle it
  • defer it up the calling chain
  • do both: handle it, but also defer it to the caller.

Example:

  • if method A calls method B, and then B calls method C, and C raises an exception:
    • C can handle it
    • C can defer it to B (the caller of C)→ B, and in turn, A, then have the same choices
    • C can handle it and then re-raise it

6

exception handling1
Exception Handling

Propagate

(report the error)

I will handle it

7

validating input2
Validating Input

Loop continues to execute, raising and handling exceptions, until user complies.

demo$ python3 e4.py

#: 5

successfullygot x: 5

#: asdf

name 'asdf' is not defined

#: 3/0

division by zero

Exception1

Exception2

exception handling2
Exception Handling

defer

Ouch!

I will handle it

9

deferring exceptions
Deferring Exceptions
  • exception raised in buggycrashes (propagates) out to whatever called it: main, in this case.
  • main catches the exception.

demo$ python3 e12.py

#? 10

0.5

demo$ python3 e12.py

#? 0

sadly, wecannot do zero division.

demo$ python3 e12.py

#? asdf

Traceback … ValueError…

10

exception handling3
Exception Handling

Propagate

(report the error)

defer

Ouch!

I will handle it

11

exception handling4
Exception Handling

Defer the rest

Defer the rest

I will handle some

I will handle some

12

deferring some exceptions
Deferring Some Exceptions
  • ValueErrors caught in buggy.
  • ZeroDivisionErrors propagated to main, caught there.
  • TypeErrors propagated all the way, crashing entire program.

demo$ python3 e13.py

#? 3

1.6666666666666667

demo$ python3 e13.py

#? "hello"

didn'tget an int!

0

demo$ python3 e13.py

#? 0

sadly, wecannot do zero division.

demo$

#? (1,2,3)

Traceback … TypeError…

13

deferring another example
Deferring - another example
  • KeyError handled in find()
  • ZeroDivisionErrordeferred in find(), then handled in main()
  • ValueErrors unhandled.

demo$ python3 e14.py

#? 6

a

demo$ python3 e14.py

#? 4

redherring

demo$ python3 e14.py

#? 0

sadly, wecannot do zero division.

demo$ python3 e14.py

#? asdf

Traceback…ValueError…

14

exception handling5
Exception Handling

Login bank account

Count failed times

Verify the password

Defer the rest

Defer the rest

I will handle some

I will handle some

If the exception is handled by C, then B will not notice it

15

exception handling6
Exception Handling

Login bank account

Count failed times

Verify the password

Re-raise

I will handle it

I will handle it, too

After the exception is handled by C, we will manually inform B

16

raising exceptions
Raising Exceptions
  • We can generate an exception on purpose(and hopefully catch it somewhere else!)
  • done with a raise statement, which needs an expression of some Exception type. This usually means calling a constructor (__init__). Examples:
    • raiseException("boo!")raiseArithmeticError ("this doesn't add up!")raiseValueError("needed a positive number")
    • except IOError as e: print ("catching it, re-raising it.")raise e
exceptions hierarchy1
Exceptions Hierarchy

BaseException

+-- KeyboardInterrupt

+-- Exception

+-- ArithmeticError

| +-- ZeroDivisionError

+-- EnvironmentError

| +-- IOError

+-- EOFError

+-- LookupError

| +-- IndexError

| +-- KeyError

+-- NameError

+-- SyntaxError

+-- SystemError

+-- TypeError

+-- ValueError

  • There are many exception classes organized into a hierarchy→ using inheritance (parent and child class relationships)
  • (found at http://docs.python.org/3.2/library/exceptions.html)

Build-in exception, everyone know what they means

raising exceptions1
Raising Exceptions

Reusing/raising a few specific exception types is useful:

  • Exception for general issues (but a bit vague)
  • TypeError, when the supplied arg. was the wrong type
  • ValueError when your code only should be run on some batch of values and the wrong one was given
  • Any of them can be reused if it suits your purpose, just call their constructor (see examples on previous slide)

Then you can raise them and catch them as before.

→ but you can also make brand new types of exceptions!

re raising the same exception
Re-raising the Same Exception
  • We can directly re-raise the caught exception object.
  • To force this exception propagate, since by default exception only get handled once
  • No need to construct an exception value-we already have an exception object.

note the quotes!

demo$ python3 e16.py

#: 'a'

in get_input: could not convert string to float: 'a'

in main:could not convert string to float: 'a'

20

re raising another exceptions
Re-raising Another Exceptions
  • Initialize an exception ourselves
    • We want to customized the error information to the caller

note the quotes!

demo$ python3 e15.py

#: 'asdf'

in get_input: could not convert string to float: 'asdf'

in main: ERR

demo$ python3 e15.py

#: (1,2,3)

in main:float() argument must be a string or a number

demo$ python3 e15.py

#: asdf

Traceback…NameError…

21

exception handling7
Exception Handling

Login bank account

Count failed times

Verify the password

Re-raise

I will handle it

I will handle it, too

After the exception is handled by C, we will manually inform B

22

exceptions and classes
Exceptions and Classes

Did you find initialization of an exception looks the same as initialization of an object of a class?

Actually exceptions are just a kind of class:

exceptions hierarchy2
Exceptions Hierarchy

BaseException

+-- KeyboardInterrupt

+-- Exception

+-- ArithmeticError

| +-- ZeroDivisionError

+-- EnvironmentError

| +-- IOError

+-- EOFError

+-- LookupError

| +-- IndexError

| +-- KeyError

+-- NameError

+-- SyntaxError

+-- SystemError

+-- TypeError

+-- ValueError

  • There are many exception classes organized into a hierarchy→ using inheritance (parent and child class relationships)
  • (found at http://docs.python.org/3.2/library/exceptions.html)

Inheritance relations

We usually define customized exception as child class of build-in ones

user defined exceptions
User-Defined Exceptions

We can create our own types of exceptions.

They can be raised, propagated, and caught just like any other exception types.

25

slide26

User-Defined Exceptions

  • raise keyword used with a call to our exception's constructor
  • except-block used with our new type of exception

demo$ python3 e11.py

#? 5

50

demo$ python3 e11.py

#? 13

uhoh: that'sunlucky!

demo$ python3 e11.py

#? asdf

invalidliteral for int() with base 10: 'asdf'

Raise an exception just like:

If want to trigger this event, then raise this exception

26

slide27

Example: using exception handling in classes

  • A class can use exceptions within its methods, just like we've done before.

demo$ python3 -i e17.py

>>> alice = Artist()

>>> alice.set_name("Alice Cooper")

too long!

slide28

Example: using instance variables in exceptions

demo$ python3 -i e18.py

>>> alice = Artist()

>>> alice.set_name("Alice Cooper")

too long! (12)

Our exceptions are objects, and they can have/use instance variables like data.