Exceptions 2 COMPSCI 105 S2 2015 Principles of Computer Science.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
Index Exception handling Exception In Java Exception Types
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions COMPSCI 105 S Principles of Computer Science.
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
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
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.
General Programming Introduction to Computing Science and Programming I.
Functions Reading/writing files Catching exceptions
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 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
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.
CS 177 Week 10 Recitation Slides 1 1 Debugging. Announcements 2 2.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
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.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Python Exceptions and bug handling Peter Wad Sackett.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
COMPSCI 107 Computer Science Fundamentals
Exceptions in Python Error Handling.
George Mason University
Why exception handling in C++?
Exceptions and files Taken from notes by Dr. Neil Moore
Exception Handling Chapter 9.
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Exceptions and files Taken from notes by Dr. Neil Moore
Exception Handling Chapter 9 Edited by JJ.
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
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.
By Ryan Christen Errors and Exceptions.
Topics Introduction to File Input and Output
Dealing with Runtime Errors
Presentation transcript:

Exceptions 2 COMPSCI 105 S Principles of Computer Science

Exception not Matched  If no matching except block is found, the run-time system will attempt to handle the exception, by terminating the program. COMPSCI 1052 def divide(a, b): try: result = a / b except IndexError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result def divide(a, b): try: result = a / b except IndexError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result x = divide(5, "5") print(x) x = divide(5, "5") print(x) Traceback (most recent call last): File "...", line 10, in x = divide(5, '5') File "...", line 3, in divide result = a / b TypeError: unsupported operand type(s) for /: 'int' and 'str' Traceback (most recent call last): File "...", line 10, in x = divide(5, '5') File "...", line 3, in divide result = a / b TypeError: unsupported operand type(s) for /: 'int' and 'str' Lecture08

Order of except clauses  Specific exception block must come before any of their general exception block COMPSCI 1053 def divide(a, b): try: result = a / b except: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result def divide(a, b): try: result = a / b except: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result File "...", line 3 result = a / b ^ SyntaxError: default 'except:' must be last File "...", line 3 result = a / b ^ SyntaxError: default 'except:' must be last Lecture08

Exceptions  Any kind of built-in error can be caught  Check the Python documentation for the complete list  Some popular errors:  ArithmeticError: various arithmetic errors  ZeroDivisionError  IndexError: a sequence subscript is out of range  TypeError: inappropriate type  ValueError: has the right type but an inappropriate value  IOError: Raised when an I/O operation  EOFError: hits an end-of-file condition (EOF) without reading any data  ……  - exception-hierarchy - exception-hierarchy COMPSCI 1054Lecture08

The Finally clause  The finally block is optional, and is not frequently used  Executed after the try and except blocks, but before the entire try-except ends  Code within a finally block is guaranteed to be executed if any part of the associated try block is executed regardless of an exception being thrown or not  It is intended to define cleanup actions that must be performed under all circumstances. COMPSCI 1055 try: statement block here except: more statements here finally: more statements here try: statement block here except: more statements here finally: more statements here Lecture08

The else clause  Executed only if the try clause completes with no errors  It is useful for code that must be executed if the try clause does not raise an exception. COMPSCI 1056 try: except :... except : except: else: finally: try: except :... except : except: else: finally: Lecture08

Example  Try statement:  Case 1:  No error  Case 2:  Divided by zero COMPSCI 1057 def divide(a, b): try: result = a / b except ZeroDivisionError: result = 'Divided by zero' else: print("result is", result) finally: print("executing finally clause") return result def divide(a, b): try: result = a / b except ZeroDivisionError: result = 'Divided by zero' else: print("result is", result) finally: print("executing finally clause") return result Lecture08 x = divide(2, 1) print(x) x = divide(2, 1) print(x) result is 2.0 executing finally clause 2.0 result is 2.0 executing finally clause 2.0 x = divide(2, 0) print(x) x = divide(2, 0) print(x) executing finally clause Divided by zero executing finally clause Divided by zero  Case 3:  Error x = divide('2', '1') print(x) x = divide('2', '1') print(x) executing finally clause Traceback (most... TypeError: unsupported operand type(s)... executing finally clause Traceback (most... TypeError: unsupported operand type(s)...

Exercise 2  What is the output of the following program when x is 1, 0 and '0'? COMPSCI 1058 def testing(x): try: print('Trying some code') y = 2 / x except ZeroDivisionError: print('ZeroDivisionError raised here') except: print('Error raised here') else: print('Else clause') finally: print('Finally') def testing(x): try: print('Trying some code') y = 2 / x except ZeroDivisionError: print('ZeroDivisionError raised here') except: print('Error raised here') else: print('Else clause') finally: print('Finally') Lecture08

Raising an exception:  You can create an exception by using the raise statement  The program stops immediately after the raise statement; and any subsequent statements are not executed.  It is normally used in testing and debugging purpose  Example: COMPSCI 1059 def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) raise Error('Error message goes here') Lecture08 Traceback (most recent call last):... raise ValueError('Invalid level!') ValueError: Invalid level! Traceback (most recent call last):... raise ValueError('Invalid level!') ValueError: Invalid level!

Example – Fraction revisited COMPSCI class Fraction: def __init__(self, top, bottom): if bottom == 0: raise ValueError("Denominator Zero") else: common = Fraction.__gcd(top, bottom) self.__num = top // common self.__den = bottom // common class Fraction: def __init__(self, top, bottom): if bottom == 0: raise ValueError("Denominator Zero") else: common = Fraction.__gcd(top, bottom) self.__num = top // common self.__den = bottom // common Lecture08 from Fraction import Fraction try: x = Fraction(2,3) print('Fraction 1 is :' + str(x)) y = Fraction(2,0) print('Fraction 2 is :' + str(y)) z = Fraction(1,4) print('Fraction 3 is :' + str(z)) Except ValueError: print('Invalid Denominator!') from Fraction import Fraction try: x = Fraction(2,3) print('Fraction 1 is :' + str(x)) y = Fraction(2,0) print('Fraction 2 is :' + str(y)) z = Fraction(1,4) print('Fraction 3 is :' + str(z)) Except ValueError: print('Invalid Denominator!') Fraction 1 is :2/3 Invalid Denominator! Fraction 1 is :2/3 Invalid Denominator! Saved in Fraction.py Saved in Example.py

 Benefits of of using exception handling  Separates the detection of an error (done in a called function) from the handling of an error (done in the calling method).  Often the called function does not know what to do in case of an error. It throws an exception to its caller.  The libirary function can detect the error, but only the caller knows what needs to be done when an error occurs.  If an exception was not caught in the current function, it is passed to its caller. The process is repeated until the exception is caught or passed to the main function (either is handled or the program disrupts and terminates without further execution). Raise and handle exceptions 11 COMPSCI 105 Lecture08

 An exception is wrapped in an object.  To throw an exception, you first create an exception object and then use the raise keyword to throw it.  This exception object can be access from the except clause with the following syntax.  Example: Using exception objects 12 COMPSCI 105 Lecture08 try: except ExceptionType as ex: try: except ExceptionType as ex: try: x = Fraction(2,3) print('Fraction 1 is :' + str(x)) y = Fraction(2,0) print('Fraction 2 is :' + str(y)) Except ValueError as ex: print("Exception: "+ str(ex)) try: x = Fraction(2,3) print('Fraction 1 is :' + str(x)) y = Fraction(2,0) print('Fraction 2 is :' + str(y)) Except ValueError as ex: print("Exception: "+ str(ex)) Fraction 1 is :2/3 Exception: Denominator Zero Fraction 1 is :2/3 Exception: Denominator Zero

Handling Exceptions  Put code that might create a runtime error is enclosed in a try block COMPSCI def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) try: checkLevel(-2) print ('This print statement will not be reached.') except ValueError as x: print ('Problem: {0}'.format(x)) def checkLevel(level): if level < 1: raise ValueError('Invalid level!') else: print (level) try: checkLevel(-2) print ('This print statement will not be reached.') except ValueError as x: print ('Problem: {0}'.format(x)) Lecture08 Problem: Invalid level!

 When to use try catch blocks?  If you are executing statements that you know are unsafe and you want the code to continue running anyway.  When to raise an exception?  When there is a problem that you can't deal with at that point in the code, and you want to "pass the buck" so the problem can be dealt with elsewhere. Using Exceptions 14COMPSCI 105 Lecture08

Exercise 3  Modify the following function that calculates the mean value of a list of numbers to ensure that the function generates an informative exception when input is unexpected. COMPSCI def mean(data): sum = 0 for element in data: sum += element mean = sum / len(data) return mean def mean(data): sum = 0 for element in data: sum += element mean = sum / len(data) return mean Lecture08

Summary  Exceptions alter the flow of control  When an exception is raised, execution stops  When the exception is caught, execution starts again  try… except blocks are used to handle problem code  Can ensure that code fails gracefully  Can ensure input is acceptable  finally  Executes code after the exception handling code COMPSCI 10516Lecture08