Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
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.
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.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lilian Blot TPOP Practical Assignment Optional, but you are strongly encourage to do it, especially if you are new to programming Available on Module.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Finding and Debugging Errors
Exceptions COMPSCI 105 S Principles of Computer Science.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
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.
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.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
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.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Exceptions cs1043. Program Exceptions When a program detects an error, what should it do? – Nothing, simply allow the program to fail. – Implement a course.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
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.
 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.
CS 177 Week 10 Recitation Slides 1 1 Debugging. Announcements 2 2.
Error Handling Tonga Institute of Higher Education.
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.
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.
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.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Exceptions in Python Error Handling.
George Mason University
Lecture 4 Python Basics Part 3.
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exception Handling.
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
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.
Python Syntax Errors and Exceptions
By Ryan Christen Errors and Exceptions.
Topics Introduction to File Input and Output
Dealing with Runtime Errors
Presentation transcript:

Cem Sahin CS

 There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

 Also known as, parsing errors…  You will most likely encounter with these during the compilation.  Example: >>> while True print 'Hello world' File " ", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax

>>> while True print 'Hello world' File " ", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax  If you get an syntax error:  Filename and line number are displayed.  The parser repeats the line and places an arrow (^) right after the token that caused the error.  In this case, a missing semicolon caused the error.

 Exceptions occur during run-time (during execution).  Cause your program to crash!...  Some examples are:  ZeroDivisionError  NameError  TypeError  Unless these are handled, an error message is displayed during execution and the program stops.

>>> 10 * (1/0) Traceback (most recent call last): File " ", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File " ", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File " ", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects

 It is possible to write programs that “takes care” of these exceptions.  Why bother? Because we don’t want our programs to crash…  This is done by using the “try” statement.  Try statement works as follows:  First, the try clause is executed.  If no exception occurs, the except clause is skipped. The execution of try statement is done!!  If an exception occurs, the program immediately skips to the except clause.

>>> def this_fails():... x = 1/0... >>> try:... this_fails()... except ZeroDivisionError as detail:... print 'Handling run-time error:', detail... Handling run-time error: integer division or modulo by zero  This program does not crash!!!

 The try... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.  This actually can be done in a different way too… (coming soon)

for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), ‘lines’ f.close()

 The “raise” statement allows the programmer to force a specified exception to occur.  Why do we want to do this?  For “programmer defined” exceptions  To test your code… >>> raise NameError('HiThere') Traceback (most recent call last): File " ", line 1, in ? NameError: HiThere

 The argument to raise is an exception class or an instance to be raised. >>> try:... raise NameError('HiThere')... except NameError:... print 'An exception flew by!'... raise... An exception flew by! Traceback (most recent call last): File " ", line 2, in ? NameError: HiThere

 If an exception occurs, a message will be printed, as shown in the previous slides, ONLY IF it is a built-in exception.  If we’re expecting to get a different type of exception, we need to define it in our program.  Example: For the GADS files, FlightNotFoundException can be defined…

 Programmers can define their own exceptions by creating a new exception class.  Exceptions should be derived from the Exceptions class, either directly or indirectly. >>> class MyError(Exception):... def __init__(self, value):... self.value = value... def __str__(self):... return repr(self.value)... >>> try:... raise MyError(2*2)... except MyError as e:... print 'My exception occurred, value:', e.value... My exception occurred, value: 4

 How do we know that it is a user defined exception? >>> raise MyError('oops!') Traceback (most recent call last): File " ", line 1, in ? __main__.MyError: ‘oops!’  It prints the name that we defined when we raise it.

 An exception causes the try statement to stop executing, which may cause some problems for the rest of the program (and most of the time, it does).  Example:  Close files that are left open.  Release any resources allocated during the run.  This is done by adding a “finally” clause after the try…except block..

>>> def divide(x, y):... try:... result = x / y... except ZeroDivisionError:... print "division by zero!"... else:... print "result is", result... finally:... print "executing finally clause"...

>>> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File " ", line 1, in ? File " ", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

Try clause Else clause Except clause Finally clause Is there an else clause? No Yes Exception occursNo exception occurs Rest of the code

PYTHON try: …….. except ZeroDivisionError as e: print “Error:”, e.value else: …….. finally: …….. raise MyError(4) JAVA try{ ……… } catch(ZeroDivisionException e){ System.out.println(“Error” + e.getMessage()); } finally{ ……… } throw new MyError(4);

 Some objects define standard clean-up actions to be taken when the object is no longer needed. for line in open("myfile.txt"): print line  Prints each line in myfile.txt  Problem with this code?  It leaves the file open…

 How to fix it?  The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. with open("myfile.txt") as f: for line in f: print line  After each with statement is executed, the file f is closed.  How can we know about these predefined actions?  They are defined in each objects documentation.

To raise an exception, or not: That is the question!…

 “8. Errors and Exceptions – Python v documentation”. Python Software Foundation. 22 November  Horstman, Cay. Big Java: Third Edition. John Wiley & Sons, Inc