Exceptions COMPSCI 105 S2 2015 Principles of Computer Science.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Topics Introduction Types of Errors Exceptions Exception Handling
CS102--Object Oriented Programming
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.
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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
COP INTERMEDIATE JAVA Exception Handling Serialization.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Handling Errors with Exception (in Java) Project 10 CSC 420.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
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.
The University of Texas – Pan American
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
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.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
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.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Why exception handling in C++?
Python’s Errors and Exceptions
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Part B – Structured Exception Handling
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
By Ryan Christen Errors and Exceptions.
Exception Handling.
Dealing with Runtime Errors
Presentation transcript:

Exceptions COMPSCI 105 S Principles of Computer Science

Exercise  Implement the __lt__ method to check the less than ('<') relationship of two Fraction objects.  Implement the __imul__ method to compute in-place multiplication ('*='). Lecture07COMPSCI 1052 x = Fraction(2,3) y = Fraction(1,2) print(y < x) z = x + y print(z) print(id(y)) print(id(x)) x *= z print(x) print(id(x)) print( x + y < z) x = Fraction(2,3) y = Fraction(1,2) print(y < x) z = x + y print(z) print(id(y)) print(id(x)) x *= z print(x) print(id(x)) print( x + y < z) True 7/ / False True 7/ / False

Learning outcomes  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime errors gracefully  'catching' an exception of the appropriate type  Generate exceptions when appropriate  raise an exception COMPSCI 1053Lecture07

Introduction  Errors occur in software programs. However, if you handle errors properly, you'll greatly improve your program’s readability, reliability and maintainability.  Python uses exceptions for error handling  Exception examples:  Attempt to divide by ZERO  Couldn’t find the specific file to read  The run-time system will attempt to handle the exception (default exception handler), usually by displaying an error message and terminating the program. COMPSCI 1054Lecture07

Handling unexpected input values  What if the function is passed a value that causes a divide by zero?  Error caused at runtime  Error occurs within the function  Problem is with the input  What can we do?  You can try to check for valid input first COMPSCI 1055 def divide(a, b): result = a / b return result x = divide(5, 0) print(x) def divide(a, b): result = a / b return result x = divide(5, 0) print(x) Traceback (most recent call last): File “...", line 5, in x = divide(5, 0) File “...", line 2, in divide result = a / b ZeroDivisionError: division by zero Traceback (most recent call last): File “...", line 5, in x = divide(5, 0) File “...", line 2, in divide result = a / b ZeroDivisionError: division by zero where reason Lecture07

Divide by zero error  Check for valid input first  Only accept input where the divisor is non-zero  What if “b” is not a number? COMPSCI 1056 def divide(a, b): if b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result def divide(a, b): if b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result def divide(a, b): if (type(b) is not int and type(b) is not float): result = "Error: divisor is not a number" elif b == 0: result = 'Error: cannot divide by zero'... def divide(a, b): if (type(b) is not int and type(b) is not float): result = "Error: divisor is not a number" elif b == 0: result = 'Error: cannot divide by zero'... Lecture07

Handling input error  Check for valid input first  What if “a” is not a number? COMPSCI 1057 def divide(a, b): if (type(b) is not int and type(b) is not float or type(a) is not int and type (a) is not float): result = ('Error: one or more operands' + \ ' is not a number') elif b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result x = divide(5, 'hello') print(x) def divide(a, b): if (type(b) is not int and type(b) is not float or type(a) is not int and type (a) is not float): result = ('Error: one or more operands' + \ ' is not a number') elif b == 0: result = 'Error: cannot divide by zero' else: result = a / b return result x = divide(5, 'hello') print(x) Lecture07

What is an Exception?  An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions at runtime.  When an error occurs within a method, the method creates an exception object and hands it off to the runtime system.  The exception object contains  information about the error, including its type and the state of the program when the error occurred.  Creating an exception object and handing it to the runtime system is called throwing an exception.  How to deal with an exception so that the program can catch the error and handle it without being forced into termination. COMPSCI 1058Lecture07

Handling exceptions  Code that might create a runtime error is enclosed in a try block  Statements are executed sequentially as normal  If an error occurs then the remainder of the code is skipped  The code starts executing again at the except clause  The exception is "caught"  Advantages of catching exceptions:  It allows us to write code on how to fix the problem  It prevents the program from automatically terminating COMPSCI 1059 try: statement block except: exception handling statements try: statement block except: exception handling statements Lecture07

Example 1  The try statement:  Case 1: No error  divide(5,5)  Case 2: Invalid input  divide(5,0), divide(5, ‘Hello’) COMPSCI def divide(a, b): try: result = a / b print ("Try-block") except: result = 'Error in input data' print ("Error") return result def divide(a, b): try: result = a / b print ("Try-block") except: result = 'Error in input data' print ("Error") return result Lecture07 x = divide(5, 'hello') print ("Program can continue to run...") print (x) x = divide(5, 'hello') print ("Program can continue to run...") print (x) Error Program can continue to run... Error in input data Error Program can continue to run... Error in input data x = divide(5, 5) print ("Program can continue to run...") print(x) x = divide(5, 5) print ("Program can continue to run...") print(x) Try-block Program can continue to run Try-block Program can continue to run

Exercise 01  What is the output of the following? COMPSCI def divide(dividend, divisor): try: quotient = dividend / divisor except: quotient = 'Error in input data' return quotient x = divide(5, 0) print(x) x = divide('hello', 'world') print(x) x = divide(5, 5) print(x) def divide(dividend, divisor): try: quotient = dividend / divisor except: quotient = 'Error in input data' return quotient x = divide(5, 0) print(x) x = divide('hello', 'world') print(x) x = divide(5, 5) print(x) Lecture07 Error in input data 1.0 Error in input data 1.0

Danger in catching all exceptions  The general except clause catching all runtime errors  Sometimes that can hide problems, which can not distinguish which types of errors it is  You can put two or more except clauses, each except block is an exception handler and handles the type of exception indicated by its argument in a program.  The runtime system invokes the exception handler when the handler is the FIRST ONE matches the type of the exception thrown.  It executes the statement inside the matched except block, the other except blocks are bypassed and continues after the try- except block. COMPSCI 10512Lecture07

Specifying the exceptions  Case 1:  No error  Case 2:  is not a number COMPSCI def divide(a, b): try: result = a / b except TypeError: result = 'Type of operands is incorrect' except ZeroDivisionError: result = 'Divided by zero' return result def divide(a, b): try: result = a / b except TypeError: 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) 1.0 x = divide('abc', 5) print(x) x = divide('abc', 5) print(x) Type of operands is incorrect  Case 3:  Divided by zero x = divide(5, 0) print(x) x = divide(5, 0) print(x) Divided by zero Lecture07