Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.

Slides:



Advertisements
Similar presentations
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Advertisements

An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Control Flow C and Data Structures Baojian Hua
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Exceptions  Standardized by ANSI (Since VW 3.0) Exception is the root of the exception hierarchy: 84 predefined exceptions. The two most important classes.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Chapter 12: Advanced Topics: Exception Handling Visual Basic.NET Programming: From Problem Analysis to Program Design.
C++ for Engineers and Scientists Third Edition
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Exceptions COMPSCI 105 S Principles of Computer Science.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 19 Handling Exceptions 6/09/09 Python Mini-Course: Lesson 19 1.
Object Oriented Programming
Chapter 12: Exception Handling
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Functions Reading/writing files Catching exceptions
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
Python Exceptions and bug handling Peter Wad Sackett.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
JavaScript and Ajax (Control Structures) Week 4 Web site:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
similar concepts, different syntax
George Mason University
Why exception handling in C++?
Chapter 14: Exception Handling
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
ERRORS AND EXCEPTIONS Errors:
Exceptions.
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Topics Introduction to File Input and Output
Presentation transcript:

Chapter 24 Exception CSC1310 Fall 2009

Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically triggered on errors. try/except try/except : catch and recover from raised by you or Python exceptions try/finally try/finally: perform cleanup actions whether exceptions occur or not raise raise: trigger an exception manually in your code assert assert: conditionally trigger an exception in your code

Exception Roles Error handling Error handling  Wherever Python detects an error it raises exceptions  Default behavior: stops program.  Otherwise, code try to catch and recover from the exception (try handler) Event notification Event notification  Can signal a valid condition (for example, in search) Special-case handling Special-case handling  Handles unusual situations Termination actions Termination actions  Guarantees the required closing-time operators (try/finally) Unusual control-flows Unusual control-flows  A sort of high-level “goto”

Example

try/except/else try: #main code to run except : #handler for exception except, : #handler for exception except (, ): #handler for exception except: #handler for exception else: # optional, runs if no exception occurs

Example >>>try: action() except NameError(): … except IndexError(): … except KeyError(): … except (AttributeError,TypeError,SyntaxError):… else: …. General catch-all clause: add empty except. It may catch unrelated to your code system exceptions. It may catch exceptions meant for other handler (system exit)

try/else else try else is used to verify if no exception occurred in try. else try You can always eliminate else by moving its logic at the end of the try block. However, if “else statement” triggers exceptions, it would be misclassified as exception in try block.

try/finally try/finallyfinally In try/finally, finally block is always run whether an exception occurs or not try: finally: Ensure some actions to be done in any case tryexceptelse It can not be used in the try with except and else.

Examples

raise raise raise triggers exceptions explicitly raise raise, # provide data to handler raise #re-raise last exception >>>try: raise ‘zero’, (3,0) except ‘zero’: print “zero argument” except ‘zero’, data: print data Last form may be useful if you want to propagate cought exception to another handler. Exception name: built-in name, string, user-defined class

Example

assert assertraise assert is a conditional raise assert, assert If evaluates to false, Python raises AssertionError with the as the exception’s extra data.

Exception Objects String-based exceptions String-based exceptions are any string object Class-based exceptions Class-based exceptions are identified with classes. They also identify categories of exceptions. object identityis String exceptions are matched by object identity: is superclass identity except Class exceptions are matched by superclass identity: except catches instances of the mentioned class and instances of all its subclasses lower in the class tree.

Class Exception Example >>>class General: pass >>>class Specific1(General): pass >>>class Specific2(General): pass >>>def raiser0(): X = General() # raise superclass instance raise X >>>def raiser1(): raise Specific1 # raise subclass instance >>>def raiser2(): X = Specific2() # raise different subclass instance raise X >>>for func in (raiser0, raiser1, raiser2): try: func() except General: import sys; print 'caught:', sys.exc_type

Built-in Exception Classes Exception Exception – top-level root superclass of exceptions. StandardError StandardError – the superclass of all built-in error exceptions. ArithmeticError – the superclass of all numeric errors. OverflowError OverflowError – a subclass that identifies a specific numeric error. >>>import exceptions >>>help(exceptions)

Nesting Exception Handlers Once the exception is caught, it’s life is over. finally finally does not kill exception – just specify code to be run on the way out.

Exception Idioms All errors are exceptions, but not all exceptions are errors. It could be signals or warnings (warnings module) >>>while True: try: line=raw_input() except EOFError: break else: # process next line raise Functions signal conditions with raise (to distinguish success or failure) try Debugging with outer try statement try: … # run program except: import sys; print sys.exc_type,sys.exc_value

Exception Design Tips Operations that commonly fail are generally wrapped in try statements(file opens, socket calls). However, you may want failures of such operations to kill your program instead of being caught and ignored if the failure is a show-stopper. Failure = useful error message. try/finally Implement termination in try/finally to guarantee its execution. try try It is sometimes convenient to wrap the call to a large function in a single try statement rather than putting many try statements inside of the function.

Do not Catch Too Much Do not catch too much (system exits, memory errors, programming mistakes, iteration stops.) import sys def bye(): sys.exit(40) try: bye() except: print “got it” print “continue” Mydictionary={…} try: x=Myditctionary[‘ok’] except: x=None #KeyError #continue Be specific in your handlers: empty except are handy, but potentially error-prone.

Do not Catch Too Little Do not use too specific handlers: you will need to add new exceptions to exception list in future. Instead, careful use of class-based exception can help here. >>>try: … except(myer1,myer2): … else … >>>try:… except SuccessCategoryName: … else: …